Skip to main content

Arbitrage and oracle reports

Arbitrageurs keep YieldBasis markets aligned with external spot prices along two complementary surfaces:

  1. Oracle-report swaps on Curve Twocrypto pools running YBOraclizedPolicy: deliver a signed Pyth Lazer update to PythReportBank and execute a corrective swap on the pool at a discounted fee.
  2. Leverage rebalancing on AMM and VirtualPool: restore AMM's collateral-to-debt ratio to 2:1 when the Curve LP token price diverges from AMM.get_p().

1. Delivering signed reports to PythReportBank​

PythReportBank is a shared, permissionless registry that verifies Pyth Lazer EVM updates and stores the newest price per (feed_id, channel) stream. Any policy reading the bank can use a stored report immediately.

Exact binary layout and limits​

Every update passed to deliver_report(bytes) must conform to Pyth Lazer's EVM envelope and payload format with exactly three properties per feed in fixed order:

SegmentConstantByte sizeLayout (big-endian)
EnvelopeENVELOPE_BYTES71[0:4] EVM_MAGIC (0x2a22999a), [4:36] r, [36:68] s, [68:69] recovery id (0 or 1), [69:71] uint16 payload length n
Payload headerHEADER_BYTES14[0:4] PAYLOAD_MAGIC (0x93c7d375), [4:12] message_us (uint64), [12:13] channel (uint8), [13:14] feed_count (1..8)
Each feed (k)FEED_BYTES27[0:4] feed_id (uint32), [4:6] 0x0300 (3 props, prop 0 price), [6:14] mantissa (int64), [14:15] 0x04 (prop 4 exponent), [15:17] exponent (int16), [17:19] 0x0c01 (prop 12 feed update time, present = 1), [19:27] observation_us (uint64)

Strict size and window bounds:

  • Feed count: 1 <= k <= MAX_FEEDS (8). Duplicate feed_id entries in one update revert with "duplicate feed".
  • Payload length: 14 + 27 * k bytes, up to MAX_PAYLOAD_BYTES = 230 bytes.
  • Total update length: 71 + 14 + 27 * k bytes, up to MAX_UPDATE_BYTES = 301 bytes. Trailing bytes after the payload revert with "update length".
  • Channels: 1 (real_time), 2 (fixed_rate@50ms), 3 (fixed_rate@200ms), 4 (fixed_rate@1000ms). Channels never share storage.
  • Verification fee: Send exact msg.value == bank.verification_fee() in wei. Overpayment or underpayment reverts with "fee".
  • Delivery window: Both message_us and every feed's observation_us (in Unix microseconds) must fall within [now_us - 60_000_000, now_us + 6_000_000] (60 seconds past to 6 seconds future, inclusive, where now_us = block.timestamp * 1_000_000). Every feed must also satisfy observation_us <= message_us.
  • Per-feed skip vs. revert: If a feed is outside the delivery window, the entire update reverts ("observation age" or "observation ahead"). If a feed is inside the window but unsupported (mantissa <= 0 or exponent outside [-18, 0]) or not strictly newer than latest[feed_id][channel].observation_us, the bank skips that feed and continues processing the rest of the update.

PythReportBank interface​

interface IPythReportBank {
function verifier() external view returns (address);
function verification_fee() external view returns (uint256);
function latest(uint32 feed_id, uint8 channel) external view returns (uint256 price, uint256 observation_us);
function decode(bytes calldata _update, uint32 _feed_id, uint8 _channel) external view returns (uint256 price, uint256 observation_us);
function deliver_report(bytes calldata _update) external payable;
}
warning

bank.decode(_update, _feed_id, _channel) is a view helper for off-chain quoting. It does not verify the cryptographic signature or the delivery time window. Never use decode() to authorize an on-chain state change; read latest(feed_id, channel) instead.

2. How YBOraclizedPolicy prices corrective swaps​

On a pool running YBOraclizedPolicy, every non-swap operation and every swap that moves price away from (or past) the reported price pays config.fee.fallback_fee (in FEE_PRECISION = 10**10, where 10**10 = 100%). A corrective swap against a fresh report earns a fee discount.

YBOraclizedPolicy fee curve across swap edge and report ageYBOraclizedPolicy fee curve across swap edge and report age

Conditions for a discounted fee​

YBOraclizedPolicy.get_fee(xp) grants a discounted fee only when all of the following hold:

  1. policy.is_killed() is false (when killed, get_fee returns 0, deferring to the pool's native fee).
  2. One pool balance rose and the other fell (_is_swap).
  3. The stored report for (FEED_ID(), CHANNEL()) is younger than config.fee.relax_time seconds and within policy.price_bounds().
  4. pool.D() matches policy.state().D (during an A ramp or after a failed best-effort removal callback, D differs and the swap pays fallback_fee until policy.sync() or the next normal callback).
  5. The crvUSD aggregator rate read from AGGREGATOR is inside [0.5e18, 2e18] (\$0.50 to \$2.00), converting coin1/USD (after optional BASIS_POOL scaling) into report_price in coin0 per coin1.
  6. The swap has positive edge at report_price and is corrective:
    • Selling coin0 for coin1 (i = 0): p_before < p_after and p_after <= report_price.
    • Selling coin1 for coin0 (i = 1): p_before > p_after and p_after >= report_price.

Exact fee formula​

Let edge be the swap's fractional advantage at report_price in FEE_PRECISION (10**10):

edge=1010−⌊input_value⋅1010output_value⌋\text{edge} = 10^{10} - \left\lfloor \frac{\text{input\_value} \cdot 10^{10}}{\text{output\_value}} \right\rfloor

For an illustrative config (query policy.config() for live parameters on any pool), YBOraclizedPolicy computes the zero-age fee:

fresh_fee=min⁡ ⁣(fallback_fee,  base_fee+⌊capture⋅max⁡(edge−base_fee, 0)1018⌋)\text{fresh\_fee} = \min\!\left(\text{fallback\_fee},\; \text{base\_fee} + \left\lfloor \frac{\text{capture} \cdot \max(\text{edge} - \text{base\_fee},\, 0)}{10^{18}} \right\rfloor\right)

As the report ages (0 < report_age_us < relax_time * 1_000_000), the discount decays with age/relax_time\sqrt{\text{age} / \text{relax\_time}}:

fee=fresh_fee+⌊(fallback_fee−fresh_fee)2⋅report_age_usrelax_time⋅106⌋+1\text{fee} = \text{fresh\_fee} + \left\lfloor \sqrt{\frac{(\text{fallback\_fee} - \text{fresh\_fee})^2 \cdot \text{report\_age\_us}}{\text{relax\_time} \cdot 10^6}} \right\rfloor + 1

Exact off-chain quoting (get_dy_with_report)​

Use policy.get_dy_with_report(i, j, dx, feed_price, report_age_us) to simulate the exact pool output before delivering a report. Pass feed_price in 1e18 USD before basis-pool scaling (the policy applies BASIS_POOL and INVERT_BASIS internally) and report_age_us = 0 when the observation timestamp is at or after block.timestamp.

interface IYBOraclizedPolicy {
function BANK() external view returns (address);
function FEED_ID() external view returns (uint32);
function CHANNEL() external view returns (uint8);
function BASIS_POOL() external view returns (address);
function INVERT_BASIS() external view returns (bool);
function is_killed() external view returns (bool);
function get_report() external view returns (uint256 asset_usd, uint256 coin0_price, uint256 observation_us);
function get_fee_with_report(uint256[2] calldata xp, uint256 feed_price, uint256 report_age_us) external view returns (uint256);
function get_dy_with_report(
uint256 i,
uint256 j,
uint256 dx,
uint256 feed_price,
uint256 report_age_us
) external view returns (uint256);
function sync() external;
}

3. Runnable ReportSwap contract (Solidity)​

The contract below decodes a signed Pyth Lazer update, delivers it to PythReportBank, swaps on the Curve Twocrypto pool, and enforces minDy in one atomic transaction.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface IERC20 {
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

interface IPythReportBank {
function verification_fee() external view returns (uint256);
function deliver_report(bytes calldata _update) external payable;
}

interface ICurveTwocrypto {
function coins(uint256 i) external view returns (address);
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy,
address receiver
) external returns (uint256);
}

contract ReportSwap {
/// @notice Atomically deliver a Pyth Lazer report and swap on a Curve Twocrypto pool.
/// @param bank Deployed PythReportBank address (read from policy.BANK()).
/// @param pool Target Curve Twocrypto pool address.
/// @param update Signed Pyth Lazer EVM update (<= 301 bytes, 1..8 feeds).
/// @param i Input coin index (0 = crvUSD, 1 = asset_token).
/// @param j Output coin index (1 - i).
/// @param dx Input amount in coin `i` native decimals.
/// @param minDy Minimum output amount in coin `j` native decimals.
/// @param receiver Recipient of output tokens.
function swapWithReport(
address bank,
address pool,
bytes calldata update,
uint256 i,
uint256 j,
uint256 dx,
uint256 minDy,
address receiver
) external payable returns (uint256 dy) {
uint256 fee = IPythReportBank(bank).verification_fee();
require(msg.value == fee, "exact fee required");

IPythReportBank(bank).deliver_report{value: fee}(update);

address coinIn = ICurveTwocrypto(pool).coins(i);
require(IERC20(coinIn).transferFrom(msg.sender, address(this), dx), "transferFrom");
require(IERC20(coinIn).approve(pool, dx), "approve");

dy = ICurveTwocrypto(pool).exchange(i, j, dx, minDy, receiver);
}
}

4. Runnable quote-and-execute script (Python)​

The script below decodes a signed Pyth Lazer EVM update via bank.decode, quotes the discounted output via policy.get_dy_with_report, and builds a ReportSwap.swapWithReport transaction.

import os
import time
from web3 import Web3

w3 = Web3(Web3.HTTPProvider(os.environ["ETH_RPC_URL"]))

POOL_ADDR = Web3.to_checksum_address(os.environ["YB_POOL"])
REPORT_SWAP_ADDR = Web3.to_checksum_address(os.environ["REPORT_SWAP_ADDR"])
# Hex-encoded Pyth Lazer EVM update fetched from your Pyth Lazer subscription
PYTH_UPDATE = bytes.fromhex(os.environ["PYTH_LAZER_UPDATE_HEX"].removeprefix("0x"))

POOL_ABI = [
{"name": "POLICY", "type": "function", "stateMutability": "view", "inputs": [], "outputs": [{"type": "address"}]},
]
POLICY_ABI = [
{"name": "BANK", "type": "function", "stateMutability": "view", "inputs": [], "outputs": [{"type": "address"}]},
{"name": "FEED_ID", "type": "function", "stateMutability": "view", "inputs": [], "outputs": [{"type": "uint32"}]},
{"name": "CHANNEL", "type": "function", "stateMutability": "view", "inputs": [], "outputs": [{"type": "uint8"}]},
{
"name": "get_dy_with_report",
"type": "function",
"stateMutability": "view",
"inputs": [
{"name": "i", "type": "uint256"},
{"name": "j", "type": "uint256"},
{"name": "dx", "type": "uint256"},
{"name": "feed_price", "type": "uint256"},
{"name": "report_age_us", "type": "uint256"},
],
"outputs": [{"type": "uint256"}],
},
]
BANK_ABI = [
{"name": "verification_fee", "type": "function", "stateMutability": "view", "inputs": [], "outputs": [{"type": "uint256"}]},
{
"name": "decode",
"type": "function",
"stateMutability": "view",
"inputs": [
{"name": "_update", "type": "bytes"},
{"name": "_feed_id", "type": "uint32"},
{"name": "_channel", "type": "uint8"},
],
"outputs": [{"name": "price", "type": "uint256"}, {"name": "observation_us", "type": "uint256"}],
},
]
REPORT_SWAP_ABI = [
{
"name": "swapWithReport",
"type": "function",
"stateMutability": "payable",
"inputs": [
{"name": "bank", "type": "address"},
{"name": "pool", "type": "address"},
{"name": "update", "type": "bytes"},
{"name": "i", "type": "uint256"},
{"name": "j", "type": "uint256"},
{"name": "dx", "type": "uint256"},
{"name": "minDy", "type": "uint256"},
{"name": "receiver", "type": "address"},
],
"outputs": [{"name": "dy", "type": "uint256"}],
}
]

pool = w3.eth.contract(address=POOL_ADDR, abi=POOL_ABI)
policy_addr = pool.functions.POLICY().call()
policy = w3.eth.contract(address=policy_addr, abi=POLICY_ABI)

bank_addr = policy.functions.BANK().call()
feed_id = policy.functions.FEED_ID().call()
channel = policy.functions.CHANNEL().call()
bank = w3.eth.contract(address=bank_addr, abi=BANK_ABI)

# 1. Decode feed price and observation timestamp from the update (view-only, no signature check)
feed_price, obs_us = bank.functions.decode(PYTH_UPDATE, feed_id, channel).call()
assert feed_price > 0, "Feed price unsupported in update"

# Estimate report age in microseconds at the next block (~12s ahead or current timestamp)
now_us = int(time.time() * 1_000_000)
report_age_us = max(0, now_us - obs_us)

# 2. Quote discounted swap output (example: 25,000 crvUSD -> asset_token)
i, j, dx = 0, 1, 25_000 * 10**18
quoted_dy = policy.functions.get_dy_with_report(i, j, dx, feed_price, report_age_us).call()
min_dy = quoted_dy * 9_990 // 10_000 # 10 bp slippage guard
verify_fee = bank.functions.verification_fee().call()

print(f"feed_price={feed_price / 1e18:,.2f} age={report_age_us / 1e6:.2f}s quoted_dy={quoted_dy} fee={verify_fee} wei")

# 3. Build calldata for ReportSwap.swapWithReport (send with value=verify_fee)
report_swap = w3.eth.contract(address=REPORT_SWAP_ADDR, abi=REPORT_SWAP_ABI)
tx = report_swap.functions.swapWithReport(
bank_addr, POOL_ADDR, PYTH_UPDATE, i, j, dx, min_dy, os.environ["SENDER_ADDR"]
).build_transaction({
"from": os.environ["SENDER_ADDR"],
"value": verify_fee,
"nonce": w3.eth.get_transaction_count(os.environ["SENDER_ADDR"]),
})
print(f"Built swapWithReport tx: gas={tx['gas']} value={tx['value']}")

5. Rebalancing AMM and VirtualPool​

When the Curve LP token price diverges from AMM.get_p(), arbitrageurs trade against AMM directly (using LP tokens and crvUSD) or against VirtualPool (using asset_token and crvUSD via an internal flash loan).

Rebalance buy path through VirtualPool, AMM, and Curve Twocrypto poolRebalance buy path through VirtualPool, AMM, and Curve Twocrypto pool Rebalance sell path through VirtualPool, AMM, and Curve Twocrypto poolRebalance sell path through VirtualPool, AMM, and Curve Twocrypto pool

Direct AMM.exchange vs. VirtualPool.exchange​

PathCoin 0Coin 1QuotingExecution mechanism
AMM.exchangecrvUSDCurve LP tokenAMM.get_dy(i, j, in_amount)Direct swap against AMM collateral and debt; charges AMM.fee() (1e18 scale)
VirtualPool.exchangecrvUSDasset_tokenVirtualPool.get_dy(i, j, in_amount)Flash-loans crvUSD from Factory.flash(), adds/removes balanced Curve LP, swaps through AMM, repays flash loan

Key execution details:

  • AMM.exchange(i, j, in_amount, min_out, _for=msg.sender):
    • i = 0, j = 1 (buy LP with crvUSD): repays AMM debt and withdraws LP collateral; in_amount cannot exceed AMM.get_debt() (AMM.get_dy(0, 1, in_amount) reverts with "Amount too large", whereas AMM.exchange(0, 1, ...) reverts with a Vyper arithmetic underflow (0x11)).
    • i = 1, j = 0 (sell LP for crvUSD): adds LP collateral and increases AMM debt.
    • Enforces the safe-debt band ([1/16, 17/32] of collateral value) unless the trade moves collateral_value / debt strictly toward 2.0 without crossing it.
  • VirtualPool.exchange(i, j, in_amount, min_out, _for=msg.sender):
    • Applies ROUNDING_DISCOUNT = 10**10 (1e-8 of 1e18) on i = 0 inputs so the flash-loan repayment never underflows due to rounding.
    • Because VirtualPool calls POOL.add_liquidity / POOL.remove_liquidity symmetrically, it does not pay the Curve pool's swap fee, only AMM.fee().