Skip to main content

Net pressure

The net-pressure system measures aggregate crvUSD net buy/sell pressure across YieldBasis markets, splits a governance-configured fraction of LT admin fees into a crvUSD reserve, and computes target incentive APRs for a sink Curve Stableswap pool. Read FeeSplitter.pid() and FeeSplitter.split_fraction() on-chain to inspect active routing, or check Contract addresses.

Architecture and distribution cycle​

Six contracts in contracts/net_pressure/ compose the stack:

ContractRole
FeeSplitter.vyInstalled as Factory.fee_receiver(). Splits split_fraction() of incoming LT admin fees to pid() and the remainder to FeeDistributor, then triggers both.
MerklPIDDriver.vyStateless PID driver for off-chain Merkl campaigns. Converts incoming LT fees to crvUSD on trigger(), exposes preview_target_apr(), and lets owner or manager create and override Merkl campaigns backed by its crvUSD reserve.
PID.vyStateful on-chain PID controller. Converts LT fees to crvUSD, advances the PID loop on trigger(), and sets FastGauge.set_reward_rate().
FastGauge.vyERC-4626 staking gauge over the sink pool LP token streaming crvUSD pulled from PID at each checkpoint.
YBNetPressure.vyManipulation-resistant net-pressure and half_tvl oracle built on AMM invariants and lp_oracle_2.
MarketRateGetter.vyBenchmark rate source (rate() -> uint256) reading the Sky Savings Rate (sUSDS.ssr()).

A full distribution cycle executes in one permissionless call to FeeSplitter.trigger() (or its alias FeeSplitter.fill_epochs()):

  1. FeeSplitter enumerates FeeDistributor's current token set via current_token_set() and token_sets(set_id, i).
  2. For each LT token, FeeSplitter makes a best-effort call to lt.withdraw_admin_fees() to mint newly accrued admin fee shares to itself.
  3. For each nonzero balance bal, it transfers to_pid = bal * split_fraction // 10**18 to pid() and bal - to_pid to fee_distributor().
  4. If pid() != address(0), it calls PID(pid).trigger(), which converts held LT shares into crvUSD (and updates FastGauge if pid() is PID.vy).
  5. It calls fee_distributor().fill_epochs() to distribute the remaining share to veYB holders.

PID controller math​

Both MerklPIDDriver.vy and PID.vy execute the same 1e18 fixed-point control law with dt expressed in years (SECONDS_PER_YEAR = 365 * 86400):

pressure=max⁡ ⁣(0, ∑net_pressure)∑half_tvl,sink=sink_tvl∑half_tvl,error=pressure−sink\text{pressure} = \frac{\max\!\left(0,\ \sum \text{net\_pressure}\right)}{\sum \text{half\_tvl}}, \qquad \text{sink} = \frac{\text{sink\_tvl}}{\sum \text{half\_tvl}}, \qquad \text{error} = \text{pressure} - \text{sink} integralk=clamp⁡ ⁣(integralk−1+error⋅Δt, 0, max_integral)\text{integral}_{k} = \operatorname{clamp}\!\left(\text{integral}_{k-1} + \text{error}\cdot\Delta t,\ 0,\ \text{max\_integral}\right) dpressure,k=Tf⋅dpressure,k−1+(pressurek−pressurek−1)Tf+Δtd_{\text{pressure},k} = \frac{T_f \cdot d_{\text{pressure},k-1} + (\text{pressure}_k - \text{pressure}_{k-1})}{T_f + \Delta t} target=min⁡ ⁣(α⋅pressurek+kp⋅error+ki⋅integralk+kd⋅max⁡(0,dpressure,k), sink_cap)\text{target} = \min\!\left(\alpha \cdot \text{pressure}_k + k_p \cdot \text{error} + k_i \cdot \text{integral}_k + k_d \cdot \max(0, d_{\text{pressure},k}),\ \text{sink\_cap}\right) offer=max⁡ ⁣(1, dead_band+targetsink_per_offer),target_apr=(offer−1)⋅market_rate\text{offer} = \max\!\left(1,\ \text{dead\_band} + \frac{\text{target}}{\text{sink\_per\_offer}}\right), \qquad \text{target\_apr} = (\text{offer} - 1) \cdot \text{market\_rate}
  • Filtered derivative (Tf=d_filter_time/SECONDS_PER_YEART_f = \text{d\_filter\_time} / \text{SECONDS\_PER\_YEAR}): Enforcing d_filter_time > 0 keeps the denominator Tf+ΔtT_f + \Delta t strictly positive even on same-block calls (Δt=0\Delta t = 0). Only rising pressure (max⁡(0,dpressure)\max(0, d_{\text{pressure}})) contributes to target.
  • Signed target: target is clamped only at the top (sink_cap), so negative values let offer drop to 1x (target_apr = 0) when no sink is needed.
  • Connection gate: MerklPIDDriver.connected() (and PID._connected()) returns True iff FACTORY.fee_receiver() is a contract whose pid() returns self. Off-chain Merkl runners check connected() before starting integration so the integral does not wind up before activation.

FeeSplitter (FeeSplitter.vy)​

FeeSplitter sits in front of FeeDistributor as Factory.fee_receiver(). It reads the active LT token set directly from fee_distributor so token lists are never duplicated.

Constants, storage, and events​

  • Constants: PRECISION = 10**18, MAX_TOKENS = 100.
  • Public storage: split_fraction() -> uint256 (1e18 = 100%), pid() -> address, fee_distributor() -> address, owner() -> address.
  • Events: SetSplitFraction(fraction), SetDestinations(pid, fee_distributor), Recover(indexed token, amount).

External functions​

Owner-only functions use snekmate ownable ("ownable: caller is not the owner").

SignatureMutabilityAccessNotes
trigger()nonpayable, @nonreentrantAnyoneRealizes LT admin fees (best-effort), splits balances by split_fraction, calls pid.trigger() (if pid != 0x0), and calls fee_distributor.fill_epochs().
fill_epochs()nonpayable, @nonreentrantAnyoneAlias of trigger() for FeeDistributor keeper compatibility.
set_split_fraction(fraction: uint256)nonpayableOwnerReverts "fraction > 1" if fraction > 10**18. Emits SetSplitFraction.
set_destinations(pid: address, fee_distributor: address)nonpayableOwnerValidates fee_distributor by calling fill_epochs(). Emits SetDestinations.
recover(token: address, amount: uint256, to: address)nonpayableOwnerTransfers amount of token to to. Emits Recover.
transfer_ownership(new_owner: address)nonpayableOwnerTransfers contract ownership.

MerklPIDDriver (MerklPIDDriver.vy)​

MerklPIDDriver holds the crvUSD incentive reserve, converts incoming LT admin fees into crvUSD, exposes the stateless PID step (preview_target_apr) and primitive signals (raw_signals) for Merkl, and manages Merkl campaigns funded via a Pull-on-Claim wrapper token.

Constants, immutables, and storage​

  • Constants: PRECISION = 10**18, FEE_DENOM = 10**10, SECONDS_PER_YEAR = 365 * 86400, MAX_POOLS = 20, MAX_TOKENS = 100, MAX_CAMPAIGN_DATA = 4096, MAX_PARAM = 10**24, MAX_FILTER_TIME = 10**9.
  • Immutables: CRVUSD() -> IERC20, FACTORY() -> Factory.
  • Wiring storage: net_pressure(), market_rate_getter(), fee_distributor(), pressure_lts(i), sink_pool() (informational only; Merkl supplies sink_tvl), manager(), merkl_creator(), reward_wrapper(), pool_approved(pool).
  • Controller parameter getters (all 1e18 except d_filter_time in seconds): feedforward_gain(), kp(), ki(), kd(), max_integral(), sink_cap(), dead_band(), sink_per_offer(), d_filter_time(), swap_fee_multiplier(), dust_floor(). Read these getters on-chain for active governance values.

Structs​

struct RawSignals:
pressure: uint256 # max(0, sum net_pressure) / half_tvl, 1e18
half_tvl: uint256 # sum of AMM half-TVL (crvUSD, 1e18)
market_rate: uint256 # market_rate_getter.rate(), 1e18

struct AprState:
target_apr: uint256 # bonus APR (1e18)
integral: int256 # next integral accumulator
prev_pressure: uint256 # next prev_pressure
d_pressure: int256 # next filtered derivative
pressure: uint256 # current pressure (monitoring)
sink: uint256 # current sink (monitoring)

Fee conversion mechanics​

trigger() checkpoints FACTORY.agg().price_w() once, iterates FeeDistributor's current token set, skips balances below dust_floor, and for each LT:

  1. Computes discount = min(swap_fee_multiplier * pool.fee() // 10**10, 10**18). On a pool running an unkilled YBOraclizedPolicy, pool.fee() returns config().fee.fallback_fee; on a pool running YBTwocryptoPolicy, it returns the pool's native fee.
  2. Withdraws shares via lt.withdraw(shares, min_assets, self) where min_assets is bounded by fair_assets * (1 - discount) using net_pressure_and_tvl(lt, agg_price).half_tvl and pool.price_oracle(). A slippage failure on withdrawal reverts trigger().
  3. Swaps asset_out to crvUSD via a best-effort raw_call to pool.exchange(1, 0, asset_out, min_dy, self). If the swap cannot meet min_dy, it is skipped so one pool cannot block conversion of others; the withdrawn asset remains recoverable by the owner.
Deployed min_dy scaling on 8-decimal markets

The repository source scales min_dy by precision1 (asset_out * precision1 * p_o // PRECISION * (PRECISION - discount) // PRECISION) for 8-decimal collateral tokens. The currently deployed MerklPIDDriver and idle LTSwapZap still run the pre-fix formula without * precision1 on 8-decimal markets; the scaling fix ships with the next driver redeploy.

External functions​

SignatureMutabilityAccessNotes
trigger()nonpayable, @nonreentrantAnyoneConverts held LT fees to crvUSD and emits Converted(crvusd_gained, reserve). Does not store PID state.
preview_target_apr(sink_tvl, integral_in, prev_pressure_in, d_pressure_in, dt) -> AprStateviewAnyoneRuns one stateless PID step using live oracle, market rate, and gains. Reverts "No pools" if summed half_tvl == 0.
raw_signals() -> RawSignalsviewAnyoneReturns (pressure, half_tvl, market_rate). Returns pressure = 0 when half_tvl == 0.
reserve() -> uint256viewAnyoneReturns CRVUSD.balanceOf(self).
connected() -> boolviewAnyoneTrue iff FACTORY.fee_receiver().pid() == self.
set_gains(feedforward_gain, kp, ki, kd, max_integral, sink_cap, dead_band, sink_per_offer, d_filter_time)nonpayableOwner or manager ("Not manager")Enforces abs(signed) <= 1e24, max_integral >= 0, sink_cap >= 0, dead_band <= 1e24, 0 < sink_per_offer <= 1e24, 0 < d_filter_time <= 1e9. Emits SetGains.
set_execution_params(swap_fee_multiplier: uint256, dust_floor: uint256)nonpayableOwner or managerRequires swap_fee_multiplier <= 1e24. Emits SetExecutionParams.
create_campaign(amount, campaign_type, start_timestamp, duration, campaign_data) -> bytes32nonpayableOwner or managerMints amount of reward_wrapper and calls merkl_creator.createCampaign(...) (start_timestamp = 0 defaults to block.timestamp). Emits CampaignCreated.
override_campaign(campaign_id, campaign_type, start_timestamp, duration, campaign_data)nonpayableOwner or managerUpdates campaign_data, duration, or start_timestamp via merkl_creator.overrideCampaign. Emits CampaignOverridden.
approve_merkl(amount: uint256)nonpayableOwner or managerSets CRVUSD allowance for reward_wrapper (reverts "No wrapper" if unset).
accept_conditions()nonpayableOwner or managerCalls merkl_creator.acceptConditions().
set_manager(manager: address)nonpayableOwnerSets or clears (0x0) the manager role. Emits SetManager.
set_merkl(creator: address, wrapper: address)nonpayableOwnerRevokes prior wrapper/creator allowances to 0, installs new pair, and grants infinite allowances (skipping 0x0). Emits SetMerkl.
set_pressure_lts(lts: DynArray[address, 20])nonpayableOwnerSets LT markets summed for net pressure. Emits SetPressureLts.
set_sink_pool(sink_pool: address)nonpayableOwnerSets informational sink_pool. Emits SetSinkPool.
set_sources(net_pressure, market_rate_getter, fee_distributor)nonpayableOwnerUpdates oracle, rate source, and token-set source. Emits SetSources.
recover(token: address, amount: uint256, to: address)nonpayableOwnerSweeps crvUSD reserve or any token to to. Emits Recover.

Companion contracts​

  • PID.vy: On-chain stateful counterpart to MerklPIDDriver.vy. Stores integral, prev_pressure, d_pressure, last_ts, and active. Reads sink_tvl = gauge.tvl_ema() * sink_pool.get_virtual_price() // 10**18, caches net_pressure_and_tvl in transient storage (_npt) across fee conversion and signal evaluation, and writes gauge.set_reward_rate(bonus_apr * staked_value // 10**18 // SECONDS_PER_YEAR). When disconnected, resets active = False and sets gauge rate to 0.
  • FastGauge.vy: ERC-4626 staking gauge over the sink pool LP token (MIN_TOTAL_SUPPLY = 10 * 10**18). Pulls crvUSD from PID capped by min(balance, allowance) so reserve depletion stops the stream without reverting. Exposes tvl_ema(), claim(), claimable_reward(), and optional 2-coin zaps (add_liquidity, remove_liquidity, remove_liquidity_one_coin).
  • YBNetPressure.vy: Exposes net_pressure_and_tvl(lt, agg_price = 0) -> (int256, uint256), net_pressure_oracle(lt, agg_price = 0), half_tvl_oracle(lt, agg_price = 0), net_pressure_naive(lt), and crvusd_value_fraction(lt). Every view probes AMM.check_nonreentrant() ("AMM reentrancy").
  • MarketRateGetter.vy: Exposes rate() -> uint256 (1e18 = 100%) derived from SUSDS_TOKEN.ssr(). Returns 0 when ssr <= 1e27.
  • DAO contracts: FeeDistributor, GaugeController, and VotingEscrow interfaces.
  • Pool policy and report bank: How YBOraclizedPolicy and YBTwocryptoPolicy affect pool.fee().
  • Events and Errors: Event signatures and revert strings across the net-pressure stack.
  • Contract addresses: Deployed addresses for FeeSplitter, MerklPIDDriver, and companion contracts.