Algo Ssstablecoinsss

AI First Flight #2
Beginner FriendlyDeFi
EXP
View results
Submission Details
Severity: medium
Valid

oracle_lib applies one hard-coded 72h TIMEOUT to every feed instead of the Chainlink heartbeat its own NatSpec requires, so mint, redeem and liquidate run on prices far past the heartbeat and the engine freezes only at 72h+1s

Root + Impact

Description

  • Every price the engine reads passes through oracle_lib._stale_check_latest_round_data (dsc_engine.vy:313 and :359). The library's NatSpec defines the intended behaviour: the engine should freeze when prices become stale, and staleness should be judged by the Chainlink feed heartbeat.

  • The check uses one constant, TIMEOUT = 72 * 3600, for every feed (oracle_lib.vy:15, :47-48). The heartbeat is never used. If the ZKsync ETH/USD and BTC/USD heartbeat is about 24h, a feed that stops updating is still accepted for about 48h after the point at which the spec treats it as stale. That heartbeat figure is an external assumption the repo cannot confirm; the PoC's engine assertions hold for any heartbeat under 48h. Throughout that window, minting, health checks, redemption and liquidation all use the frozen price. The engine does freeze, but late: only at 72h + 1s.

# src/oracle_lib.vy:7-9 (NatSpec - the stated design)
If a price is stale, functions will revert, and render the DSCEngine unusable - this is by design.
We want the DSCEngine to freeze if prices become stale. We should use the Chainlink feed heartbeat
to determine if a feed is stale or not.
​
# src/oracle_lib.vy:15
@>TIMEOUT: constant(uint256) = 72 * 3600
​
# src/oracle_lib.vy:47-48
@> seconds_since: uint256 = block.timestamp - updated_at
@> assert seconds_since <= TIMEOUT, "DSCEngine_StalePrice"

Risk

Likelihood:

  • This occurs when a Chainlink feed stops updating for longer than its heartbeat (an oracle or network incident) while the market moves. While the feed is working, deviation-triggered updates keep the price current.

  • No attacker can cause the outage. Once it happens, anyone can mint or liquidate inside the window.

Impact:

  • Over-minting and missed liquidations. ETH/USD is frozen at $2,000 for 48h while the market is at $1,500. A user mints 1,000 DSC on 1 WETH: the engine sees HF 1.0, but real collateral is 150% against the required 200% (real HF 0.75). The same mint reverts at a fresh $1,500. A victim at real HF 0.8333 reads as 1.1111, so liquidate reverts DSCEngine__HealthFactorOk. If the real price falls below 50% of the stale price within the window (shown at $900), the minted DSC is unbacked: $100 per WETH in the PoC.

  • Wrongful liquidations. ETH/USD is frozen low at $1,700 for 48h while the market is at $2,200. A victim who is healthy at market (HF 1.2222, liquidation reverts at a fresh $2,200) is liquidated for 450 DSC and loses 0.291176 WETH, which is $640.59 at market: a 42.4% premium instead of the 10% bonus. That victim was already liquidatable when $1,700 was fresh. The added harm is that the liquidation lands inside the window a heartbeat-based check would have frozen.

Proof of Concept

The PoC deploys the real dsc_engine.vy, decentralized_stable_coin.vy and oracle_lib.vy with the repo mocks; only WETH is deposited. Feed age is produced with boa.env.time_travel and no feed update. As a contrast, it compiles an in-memory copy of oracle_lib.vy with TIMEOUT = 25 * 3600 (24h heartbeat + 1h buffer). On the same 48h-old feed, the original accepts the price and the copy reverts DSCEngine_StalePrice.

Run from the repo root: .venv/Scripts/python poc/poc_AS-04.py

"""
PoC AS-04: oracle_lib uses one fixed 72h TIMEOUT for every feed instead of the
feed heartbeat its own NatSpec calls for, so the engine keeps minting,
liquidating and refusing liquidations on a price that stopped updating long
after the heartbeat expired. It freezes only at 72h + 1s.
​
oracle_lib.vy:7-9 "We want the DSCEngine to freeze if prices become stale.
We should use the Chainlink feed heartbeat to determine
if a feed is stale or not."
oracle_lib.vy:15 TIMEOUT: constant(uint256) = 72 * 3600
oracle_lib.vy:47-48 assert block.timestamp - updated_at <= TIMEOUT
dsc_engine.vy:313, :359 use that check for every token/feed.
​
EXTERNAL ASSUMPTION (not verifiable from the repo): the Chainlink ETH/USD and
BTC/USD heartbeat on ZKsync is ~24h. HEARTBEAT below is that assumption; every
"stale" scenario uses a 48h-old price (2x the assumed heartbeat, 24h before the
72h bound). The library-bound and engine-acceptance assertions do not depend on
the heartbeat value; they hold for any heartbeat < 48h.
​
Uses the real in-scope contracts with the repo's MockV3Aggregator (8 decimals)
and mock_token (18-decimal WETH). Only WETH is used, so the separate decimals
issue (AS-01) does not affect any number here.
​
Run (from the repo root): .venv/Scripts/python poc/poc_AS-04.py
"""
import subprocess
import sys
​
# Windows non-UTF-8 locales cannot read snekmate's UTF-8 sources with the
# default codec; re-run once in Python UTF-8 mode.
if not sys.flags.utf8_mode:
sys.exit(subprocess.call([sys.executable, "-X", "utf8", *sys.argv]))
​
import boa
​
ENGINE = "src/dsc_engine.vy"
DSC_SRC = "src/decentralized_stable_coin.vy"
ORACLE_LIB = "src/oracle_lib.vy"
MOCK_TOKEN = "src/mocks/mock_token.vy"
MOCK_FEED = "src/mocks/MockV3Aggregator.vy"
​
E18 = 10**18
HOUR = 3600
TIMEOUT = 72 * HOUR # the library's constant
HEARTBEAT = 24 * HOUR # ASSUMED Chainlink heartbeat (external, conf M)
STALE_AGE = 48 * HOUR # age of the frozen price in the scenarios
​
​
def px(usd):
return usd * 10**8 # 8-decimal Chainlink-style answer
​
​
def usd(wei):
return wei / E18
​
​
# ------------------------------------------------------------------ deploy
dsc = boa.load(DSC_SRC)
weth = boa.load(MOCK_TOKEN)
wbtc = boa.load(MOCK_TOKEN) # second collateral slot; never deposited here
eth_feed = boa.load(MOCK_FEED, 8, px(2_000))
btc_feed = boa.load(MOCK_FEED, 8, px(100_000))
engine = boa.load(
ENGINE,
[wbtc.address, weth.address],
[btc_feed.address, eth_feed.address],
dsc.address,
)
dsc.set_minter(engine.address, True)
dsc.transfer_ownership(engine.address)
lib = boa.load(ORACLE_LIB) # the library on its own (it has an external entry point)
​
# Same library with a heartbeat-based bound (24h + 1h buffer): the NatSpec's intent.
with open(ORACLE_LIB, encoding="utf-8") as f:
lib_src = f.read()
assert "TIMEOUT: constant(uint256) = 72 * 3600" in lib_src
fixed_src = lib_src.replace(
"TIMEOUT: constant(uint256) = 72 * 3600", "TIMEOUT: constant(uint256) = 25 * 3600"
)
lib_fixed = boa.loads(fixed_src, name="oracle_lib_heartbeat", filename="src/oracle_lib_heartbeat.vy")
​
​
def fund_and_deposit(who, amount):
with boa.env.prank(who):
weth.mint_amount(amount)
weth.approve(engine.address, amount)
engine.deposit_collateral(weth.address, amount)
​
​
def feed_age(feed):
return boa.env.evm.patch.timestamp - feed.latestRoundData()[3]
​
​
def real_hf(debt, weth_amt, real_price_usd):
# engine formula with the real market price
if debt == 0:
return 2**256 - 1
return (weth_amt * real_price_usd * 50 // 100) * E18 // debt
​
​
# ------------------------------------------------------------------ 0. the library bound is exactly 72h for any feed
print("== 0. oracle_lib bound: one fixed 72h window, same for every feed ==")
with boa.env.anchor():
eth_feed.updateAnswer(px(2_000))
btc_feed.updateAnswer(px(100_000))
boa.env.time_travel(seconds=TIMEOUT)
for name, feed in (("ETH/USD", eth_feed), ("BTC/USD", btc_feed)):
r = lib.stale_check_latest_round_data(feed.address)
assert r[1] == feed.latestAnswer()
print(f"{name}: age {feed_age(feed) // HOUR}h ({feed_age(feed)} s) -> accepted, price {r[1] / 1e8:,.0f}")
boa.env.time_travel(seconds=1)
for name, feed in (("ETH/USD", eth_feed), ("BTC/USD", btc_feed)):
with boa.reverts("DSCEngine_StalePrice"):
lib.stale_check_latest_round_data(feed.address)
print(f"{name}: age {feed_age(feed)} s (72h+1s) -> DSCEngine_StalePrice")
​
# ------------------------------------------------------------------ common position setup at T0 (fresh $2,000)
victim = boa.env.generate_address("victim")
fund_and_deposit(victim, 1 * E18)
with boa.env.prank(victim):
engine.mint_dsc(900 * E18) # HF = 1000/900 = 1.111 at $2,000
liq = boa.env.generate_address("liquidator")
fund_and_deposit(liq, 100 * E18)
with boa.env.prank(liq):
engine.mint_dsc(5_000 * E18)
dsc.approve(engine.address, 5_000 * E18)
assert feed_age(eth_feed) == 0
print(f"T0: ETH feed fresh at $2,000; victim 1 WETH / 900 DSC, HF {engine.health_factor(victim) / E18:.4f}")
​
# ------------------------------------------------------------------ A. feed freezes at $2,000, market falls to $1,500
print("== A. feed frozen at $2,000 for 48h (2x assumed heartbeat); market $1,500 ==")
REAL_A = 1_500
attacker = boa.env.generate_address("attacker")
​
# A-baseline: what the engine does with a current $1,500 price
with boa.env.anchor():
boa.env.time_travel(seconds=STALE_AGE)
eth_feed.updateAnswer(px(REAL_A))
fund_and_deposit(attacker, 1 * E18)
with boa.env.prank(attacker):
with boa.reverts("DSCEngine__BreaksHealthFactor"):
engine.mint_dsc(1_000 * E18)
print("baseline (fresh $1,500): attacker mint of 1,000 DSC on 1 WETH -> DSCEngine__BreaksHealthFactor")
hf_v = engine.health_factor(victim)
assert hf_v < E18
with boa.env.prank(liq):
engine.liquidate(weth.address, victim, 450 * E18)
print(f"baseline (fresh $1,500): victim HF {hf_v / E18:.4f} -> liquidate(450 DSC) succeeds")
​
# A-stale: the same actions 48h after the last update, feed never moved
boa.env.time_travel(seconds=STALE_AGE)
age = feed_age(eth_feed)
assert age == STALE_AGE and HEARTBEAT < age < TIMEOUT
r = lib.stale_check_latest_round_data(eth_feed.address)
assert r[1] == px(2_000)
with boa.reverts("DSCEngine_StalePrice"):
lib_fixed.stale_check_latest_round_data(eth_feed.address)
print(f"feed age {age // HOUR}h: oracle_lib (72h) ACCEPTS $2,000; heartbeat-based copy (25h) -> DSCEngine_StalePrice")
​
with boa.env.anchor():
# A1. over-mint against the stale price
fund_and_deposit(attacker, 1 * E18)
with boa.env.prank(attacker):
engine.mint_dsc(1_000 * E18)
assert dsc.balanceOf(attacker) == 1_000 * E18
assert engine.health_factor(attacker) == E18 # engine view: exactly 200%
rhf = real_hf(1_000 * E18, 1 * E18, REAL_A)
assert rhf == 75 * 10**16 # real: 150%, HF 0.75 < 1
print(f"A1 over-mint: 1 WETH (real ${REAL_A:,}) -> 1,000 DSC minted; engine HF 1.0000, real HF {rhf / E18:.4f} "
f"(150% collateral vs 200% required)")
​
# A2. missed liquidation: victim is underwater at market but reads as healthy
rhf_v = real_hf(900 * E18, 1 * E18, REAL_A)
assert rhf_v < E18
assert engine.health_factor(victim) > E18
with boa.env.prank(liq):
with boa.reverts("DSCEngine__HealthFactorOk"):
engine.liquidate(weth.address, victim, 450 * E18)
print(f"A2 missed liquidation: victim real HF {rhf_v / E18:.4f}, engine HF {engine.health_factor(victim) / E18:.4f} "
f"-> liquidate reverts DSCEngine__HealthFactorOk")
​
# A3. the engine freezes only after 72h + 1s
boa.env.time_travel(seconds=TIMEOUT - STALE_AGE)
assert feed_age(eth_feed) == TIMEOUT
with boa.env.prank(liq):
engine.mint_dsc(1 * E18) # still accepted at exactly 72h
boa.env.time_travel(seconds=1)
with boa.env.prank(liq):
with boa.reverts("DSCEngine_StalePrice"):
engine.mint_dsc(1 * E18)
with boa.reverts("DSCEngine_StalePrice"):
engine.liquidate(weth.address, victim, 450 * E18)
print("A3 freeze: mint still accepted at age 72h; at 72h+1s mint/liquidate -> DSCEngine_StalePrice")
​
# ------------------------------------------------------------------ B. extreme move: bad debt (needs real < 50% of stale)
print("== B. same 48h-stale $2,000, market $900 (-55%): bad debt ==")
with boa.env.anchor():
REAL_B = 900
fund_and_deposit(attacker, 1 * E18)
with boa.env.prank(attacker):
engine.mint_dsc(1_000 * E18)
debt = engine.user_to_dsc_minted(attacker)
real_coll = 1 * E18 * REAL_B # wei-USD
assert debt == 1_000 * E18 and real_coll < debt
print(f"B: attacker paid 1 WETH (${REAL_B}) and holds {usd(dsc.balanceOf(attacker)):,.0f} DSC; "
f"position collateral ${usd(real_coll):,.0f} < debt ${usd(debt):,.0f} -> no profitable liquidation, "
f"${usd(debt - real_coll):,.0f} unbacked DSC")
​
# ------------------------------------------------------------------ C. feed frozen LOW, market rises: wrongful liquidation
print("== C. feed last updated to $1,700, frozen 48h; market $2,200 ==")
# new timeline T1 (= T0 + 48h): both feeds update, ETH/USD to $1,700, then both freeze
with boa.env.anchor():
REAL_C = 2_200
eth_feed.updateAnswer(px(1_700)) # fresh at T1; victim HF 0.9444
btc_feed.updateAnswer(px(100_000)) # BTC feed is read too (zero balance)
hf_at_t1 = engine.health_factor(victim)
assert hf_at_t1 < E18
boa.env.time_travel(seconds=STALE_AGE)
assert HEARTBEAT < feed_age(eth_feed) < TIMEOUT
rhf_v = real_hf(900 * E18, 1 * E18, REAL_C)
assert rhf_v > E18 # healthy at market
# baseline: with a current $2,200 price the victim cannot be liquidated
with boa.env.anchor():
eth_feed.updateAnswer(px(REAL_C))
with boa.env.prank(liq):
with boa.reverts("DSCEngine__HealthFactorOk"):
engine.liquidate(weth.address, victim, 450 * E18)
print(f"baseline (fresh $2,200): victim HF {rhf_v / E18:.4f} -> liquidate reverts DSCEngine__HealthFactorOk")
# stale: liquidation goes through at $1,700
liq_weth_before = weth.balanceOf(liq)
victim_coll_before = engine.get_collateral_balance_of_user(victim, weth.address)
with boa.env.prank(liq):
engine.liquidate(weth.address, victim, 450 * E18)
seized = weth.balanceOf(liq) - liq_weth_before
lost = victim_coll_before - engine.get_collateral_balance_of_user(victim, weth.address)
assert seized == lost and seized > 0
seized_real = seized * REAL_C # wei-USD at market
assert seized_real > 450 * E18 * 110 // 100 # more than debt + 10% bonus at market
print(f"stale ($1,700, age {feed_age(eth_feed) // HOUR}h): liquidate(450 DSC) succeeds; victim loses "
f"{seized / E18:.6f} WETH = ${usd(seized_real):,.2f} at market for $450 of debt "
f"(premium {usd(seized_real) / 450 - 1:.1%} vs 10% bonus)")
​
print("PASS: AS-04 - engine runs on prices 48h old (past the assumed 24h heartbeat) and freezes only at 72h+1s")

The script ends with: PASS: AS-04 - engine runs on prices 48h old (past the assumed 24h heartbeat) and freezes only at 72h+1s

Recommended Mitigation

Pass a per-feed maximum age (the feed's heartbeat plus a small buffer), set at construction, instead of one global constant.

--- a/src/oracle_lib.vy
+++ b/src/oracle_lib.vy
@@ constants @@
-TIMEOUT: constant(uint256) = 72 * 3600
@@ def stale_check_latest_round_data @@
def stale_check_latest_round_data(
chainlink_feed: address,
+ max_age: uint256,
) -> (uint80, int256, uint256, uint256, uint80):
- return self._stale_check_latest_round_data(chainlink_feed)
+ return self._stale_check_latest_round_data(chainlink_feed, max_age)
@@ def _stale_check_latest_round_data @@
def _stale_check_latest_round_data(
price_price_address: address,
+ max_age: uint256,
) -> (uint80, int256, uint256, uint256, uint80):
@@
seconds_since: uint256 = block.timestamp - updated_at
- assert seconds_since <= TIMEOUT, "DSCEngine_StalePrice"
+ assert seconds_since <= max_age, "DSCEngine_StalePrice"
--- a/src/dsc_engine.vy
+++ b/src/dsc_engine.vy
@@ storage @@
token_address_to_price_feed: public(HashMap[address, address])
+token_address_to_max_price_age: public(HashMap[address, uint256])
@@ def __init__ @@
def __init__(
token_addresses: address[2],
price_feed_addresses: address[2],
+ max_price_ages: uint256[2],
dsc_address: address,
):
@@
+ self.token_address_to_max_price_age[token_addresses[0]] = max_price_ages[0]
+ self.token_address_to_max_price_age[token_addresses[1]] = max_price_ages[1]
@@ def _get_usd_value and def _get_token_amount_from_usd (both call sites) @@
(
round_id, price, started_at, updated_at, answered_in_round
- ) = oracle_lib._stale_check_latest_round_data(price_feed.address)
+ ) = oracle_lib._stale_check_latest_round_data(
+ price_feed.address, self.token_address_to_max_price_age[token]
+ )
Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge about 1 hour ago
Submission Judgement Published
Validated
Assigned finding tags:

[M-01] The TIMEOUT is set as a fixed constant of 72 hours, which makes it inflexible in adapting to the market price.

## Description In this contract, the TIMEOUT is set as a fixed constant (72 hours, or 259200 seconds). This means that if the oracle price data is not updated within 72 hours, the data will be considered outdated, and the contract will trigger a revert. ## Vulnerability Details At this location in the code, <https://github.com/Cyfrin/2024-12-algo-ssstablecoinsss/blob/4cc3197b13f1db728fd6509cc1dcbfd7a2360179/src/oracle_lib.vy#L15> ```Solidity TIMEOUT: constant(uint256) = 72 * 3600 ``` the timeout is directly set to 72 hours. For an oracle, which cannot dynamically adjust the price updates, this is a suboptimal approach. ## Impact - Fixed Timeout: The TIMEOUT is hardcoded to 72 hours. In markets with frequent fluctuations or assets that require more frequent price updates, 72 hours might be too long. Conversely, if the timeout is too short, it could cause frequent errors due to the inability to update data in time, disrupting normal contract operations. - Non-adjustable Timeout: If the contract's requirements change (e.g., market conditions evolve or the protocol requires more flexibility), the fixed TIMEOUT cannot be dynamically adjusted, leading to potential mismatches with current needs. - Lack of Flexibility: The current timeout mechanism is static and cannot be adjusted based on market volatility or the frequency of oracle updates. In volatile markets, a shorter TIMEOUT might be necessary, while in stable markets, a longer timeout would be more appropriate. \##Tools Used Manual review ## Recommendations Introduce a dynamic price expiration mechanism that adjusts based on market conditions. Use volatility data (such as standard deviation or market price fluctuation) to dynamically adjust the timeout period. This can be achieved by monitoring market volatility and adjusting the TIMEOUT accordingly: ```Solidity # Monitor market volatility and dynamically adjust TIMEOUT @external def adjustTimeoutBasedOnVolatility(volatility: uint256): if volatility > HIGH_VOLATILITY_THRESHOLD: self.TIMEOUT = SHORTER_TIMEOUT # In high volatility, decrease TIMEOUT else: self.TIMEOUT = LONGER_TIMEOUT # In stable market, increase TIMEOUT log TimeoutAdjusted(self.TIMEOUT) ```

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.

Give us feedback!