Arbitrage and oracle reports
Arbitrageurs keep YieldBasis markets aligned with external spot prices along two complementary surfaces:
- Oracle-report swaps on Curve Twocrypto pools running
YBOraclizedPolicy: deliver a signed Pyth Lazer update toPythReportBankand execute a corrective swap on the pool at a discounted fee. - Leverage rebalancing on
AMMandVirtualPool: restoreAMM's collateral-to-debt ratio to 2:1 when the Curve LP token price diverges fromAMM.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:
| Segment | Constant | Byte size | Layout (big-endian) |
|---|---|---|---|
| Envelope | ENVELOPE_BYTES | 71 | [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 header | HEADER_BYTES | 14 | [0:4] PAYLOAD_MAGIC (0x93c7d375), [4:12] message_us (uint64), [12:13] channel (uint8), [13:14] feed_count (1..8) |
Each feed (k) | FEED_BYTES | 27 | [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). Duplicatefeed_identries in one update revert with"duplicate feed". - Payload length:
14 + 27 * kbytes, up toMAX_PAYLOAD_BYTES = 230bytes. - Total update length:
71 + 14 + 27 * kbytes, up toMAX_UPDATE_BYTES = 301bytes. 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_usand every feed'sobservation_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, wherenow_us = block.timestamp * 1_000_000). Every feed must also satisfyobservation_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 <= 0orexponentoutside[-18, 0]) or not strictly newer thanlatest[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;
}
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.
Conditions for a discounted fee
YBOraclizedPolicy.get_fee(xp) grants a discounted fee only when all of the following hold:
policy.is_killed()isfalse(when killed,get_feereturns0, deferring to the pool's native fee).- One pool balance rose and the other fell (
_is_swap). - The stored report for
(FEED_ID(), CHANNEL())is younger thanconfig.fee.relax_timeseconds and withinpolicy.price_bounds(). pool.D()matchespolicy.state().D(during anAramp or after a failed best-effort removal callback,Ddiffers and the swap paysfallback_feeuntilpolicy.sync()or the next normal callback).- The
crvUSDaggregator rate read fromAGGREGATORis inside[0.5e18, 2e18](\$0.50to\$2.00), convertingcoin1/USD(after optionalBASIS_POOLscaling) intoreport_priceincoin0percoin1. - The swap has positive
edgeatreport_priceand is corrective:- Selling
coin0forcoin1(i = 0):p_before < p_afterandp_after <= report_price. - Selling
coin1forcoin0(i = 1):p_before > p_afterandp_after >= report_price.
- Selling
Exact fee formula
Let edge be the swap's fractional advantage at report_price in FEE_PRECISION (10**10):
For an illustrative config (query policy.config() for live parameters on any pool), YBOraclizedPolicy computes the zero-age fee:
As the report ages (0 < report_age_us < relax_time * 1_000_000), the discount decays with :
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).
Direct AMM.exchange vs. VirtualPool.exchange
| Path | Coin 0 | Coin 1 | Quoting | Execution mechanism |
|---|---|---|---|---|
AMM.exchange | crvUSD | Curve LP token | AMM.get_dy(i, j, in_amount) | Direct swap against AMM collateral and debt; charges AMM.fee() (1e18 scale) |
VirtualPool.exchange | crvUSD | asset_token | VirtualPool.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 withcrvUSD): repaysAMMdebt and withdraws LP collateral;in_amountcannot exceedAMM.get_debt()(AMM.get_dy(0, 1, in_amount)reverts with"Amount too large", whereasAMM.exchange(0, 1, ...)reverts with a Vyper arithmetic underflow (0x11)).i = 1, j = 0(sell LP forcrvUSD): adds LP collateral and increasesAMMdebt.- Enforces the safe-debt band (
[1/16, 17/32]of collateral value) unless the trade movescollateral_value / debtstrictly toward2.0without crossing it.
VirtualPool.exchange(i, j, in_amount, min_out, _for=msg.sender):- Applies
ROUNDING_DISCOUNT = 10**10(1e-8of1e18) oni = 0inputs so the flash-loan repayment never underflows due to rounding. - Because
VirtualPoolcallsPOOL.add_liquidity/POOL.remove_liquiditysymmetrically, it does not pay the Curve pool's swap fee, onlyAMM.fee().
- Applies