Verified contractPartialMIT
JitProbeV12
Address0x9c3e0469ae5e4ccb1a86ccbfbb8d153bf3c4c7b9
- Balance
0 ETH
- Transactions
109
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 1,000 runs
- EVM version
- osaka
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,350,447
- Creation transaction
- 0xb186259b37…36bc1dc8f5
4 files
- src/probe/JitProbeV12.solmain20.4 KB
- src/interfaces/IJITSettler.sol1.94 KB
- src/libraries/SafeERC20Min.sol1.19 KB
- src/probe/JitProbe.sol18.76 KB
src/probe/JitProbeV12.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { IJITSettler } from "../interfaces/IJITSettler.sol";
import { SafeERC20Min } from "../libraries/SafeERC20Min.sol";
import { IAllowance } from "./JitProbe.sol";
/// @title JitProbe v12 (production smoke test)
/// @notice Makes the integration guide's call on a production builder with real tokens: try
/// `JITSettler.swap` with `recipient = this`; on any revert, run the aggregator's call for
/// real. Not part of the deployment set and not in the bytecode pins (`tools/pin.py`).
///
/// measure agents only, reentrancy-locked; emits the outcome
/// └ runIntegrator SelfOnly; commits. A failure here is `MeasureFailed`
/// ├ JIT attempt `JITSettler.swap`, committed when it fills
/// └ fallback `aggTarget`, once, committed, only when `swap` reverted
///
/// What differs from `JitProbeV11`'s `INTEGRATOR` mode, which must never hold a balance:
///
/// THE FLOOR. The builder reads what the fallback paid this contract as `simOriginalOut`.
/// 0x takes its fee before paying its taker, so that figure is net of the fee, while a
/// real integrator's fallback delivers the gross amount to the contract that then pays
/// the fee (`SELECT` in 0x's Settler). `minOut` is how the gross figure gets in: the
/// driver sends `buyAmount + zeroExFee`, jit-router refuses a route below
/// `max(minOut, simOriginalOut)`, and the settler enforces the same floor. The route's
/// gain against gas is still measured from `simOriginalOut`, so a route within the fee of
/// its gas cost can pass here where a real integrator's would not.
///
/// REAL FUNDS. `measure` relays calldata from an aggregator's API, so what stands in for
/// an empty balance is:
/// - the admin allowlists each `aggTarget` and `aggSpender`; a target is a contract that
/// does not let a caller's calldata act as this contract (0x's AllowanceHolder),
/// so nothing relayed can call a token's `approve` as this contract;
/// - `maxAmountIn` caps one call per token, and 0 refuses the token, as input or output;
/// - a token cannot be a target, nor a target a token, so no target can be a capped token
/// and call its `approve`;
/// - the fallback must deliver at least `aggMinOut`, or `runIntegrator` reverts and every
/// token stays here. The agent supplies it from the same quote, so this catches a stale
/// or mispriced route, not an agent or API that lies. The balance is what bounds that,
/// so keep it to what the grid needs;
/// - the approvals are exactly `amountIn` and zero on every path.
///
/// Sweep what is left when the test ends, and retire the contract.
contract JitProbeV12 {
using SafeERC20Min for address;
/// @notice This contract's version, readable on chain.
uint256 public constant VERSION = 12;
/// @notice The error value for a call that reverted with no selector: no data (out of gas,
/// bare `revert()`, failed `assert`), under 4 bytes, or a first 4 bytes of zero.
/// Distinct from `bytes4(0)`, which means the call did not revert.
bytes4 public constant BARE_REVERT_MARK = 0xffffffff;
/// @notice The error value for an aggregator call that failed
/// having used all of its bound (within `AGG_CAP_EPSILON`), whatever it reverted
/// with: truncated by our bound, never an ordinary aggregator loss.
bytes4 public constant EXT_CAP_MARK = 0xfffffffe;
/// @notice The most revert data the aggregator call copies: bounded so a target reverting
/// with a huge payload cannot make the probe pay to copy it.
uint256 public constant MAX_REASON_LEN = 164;
/// @dev Gas kept back after a bounded aggregator call, for the post-call `balanceOf` (cold)
/// and what follows; EIP-150's 1/64 alone may not cover them near the bottom of the
/// budget.
uint256 internal constant AGG_TAIL_RESERVE = 50_000;
/// @dev A failed bounded call that left less than this of what it was forwarded is a cap
/// hit (the callee's last opcodes after its own out-of-gas check).
uint256 internal constant AGG_CAP_EPSILON = 2000;
/// @notice What filled a probe. The value is the ABI: 0, 1, 2. `ROUTED`: `swap` returned.
/// `FALLBACK`: `swap` reverted and the aggregator paid this contract at least
/// `aggMinOut`. `NONE`: `swap` and the aggregator's call both reverted.
enum FillPath {
ROUTED,
FALLBACK,
NONE
}
/// @notice One probe. Field ORDER is the ABI: the driver encodes it.
/// @param tag The driver's per-send id (`keccak256(quote_id)`), joins sends to outcomes.
/// @param minOut `Request.minOut`: the floor the route must clear, at least `aggMinOut`. See
/// THE FLOOR above.
/// @param aggSpender Approved for exactly `amountIn` around the aggregator call. Allowlisted.
/// @param aggTarget,aggData The aggregator's transaction, called verbatim. Its taker must be
/// this contract. `aggTarget` is allowlisted.
/// @param aggMinOut The least the fallback may deliver here; not 0.
/// @param aggGasLimit The most gas the aggregator call may use; not 0.
/// @param jitMaxGas `Request.maxGas` and the gas forwarded to `swap`; not 0.
struct Params {
bytes32 tag;
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 minOut;
address aggSpender;
address aggTarget;
bytes aggData;
uint256 aggMinOut;
uint256 aggGasLimit;
uint256 jitMaxGas;
}
/// @notice What `runIntegrator` returns.
struct IntegratorOutcome {
FillPath path;
uint256 delivered;
bytes4 swapError;
uint256 swapGas;
bytes4 fallbackError;
uint256 fallbackGas;
}
/// @notice The `JITSettler` under test.
address public immutable SETTLER;
/// @notice Administers agents, targets, caps, ownership and `sweep`; cannot `measure` unless
/// also an agent.
address public admin;
/// @notice Nominated by `nominateAdmin`; becomes `admin` on `claimAdmin`.
address public pendingAdmin;
/// @notice The addresses allowed to call `measure`.
mapping(address => bool) public isAgent;
/// @notice The contracts `aggTarget` and `aggSpender` may name.
mapping(address => bool) public isTarget;
/// @notice The most one `measure` may spend of a token; 0 refuses it.
mapping(address => uint256) public maxAmountIn;
// hex of "JitProbeLock": the transient lock slot is named by its contract
uint256 private constant _LOCK_SLOT = 0x4a697450726f62654c6f636b;
error NotAdmin();
error NotPendingAdmin();
error NotAgent();
error SelfOnly();
/// @dev `aggTarget` or `aggSpender` is not allowlisted, or is this contract.
error BadTarget();
/// @dev `amountIn` is 0 or above `maxAmountIn[tokenIn]`.
error OverCap(uint256 amountIn, uint256 cap);
/// @dev `tokenOut` has no cap, so it is not a token this probe trades, and a `balanceOf` read
/// on it would prove nothing.
error BadToken(address token);
/// @dev `aggMinOut` is 0, or `minOut` is below it.
error BadFloor(uint256 minOut, uint256 aggMinOut);
/// @dev `aggGasLimit` or `jitMaxGas` is 0: this contract never forwards all its gas.
error BadGas();
/// @dev A target that is a capped token, a token that is a target, a target without code, or
/// the settler as a target.
error BadConfig(address account);
/// @dev Less than `amountIn` of `tokenIn` here.
error Underfunded(uint256 have, uint256 need);
/// @dev The fallback's call returned and delivered less than `aggMinOut`.
error FallbackShort(uint256 delivered, uint256 aggMinOut);
/// @notice One probe. Same signature as `JitProbeV11`'s, so the sink and the driver read it
/// alike. `delivered` is this contract's `tokenOut` delta. `swapError` and
/// `fallbackError` are 0 when that call did not revert; `fallbackGas` is 0 when the
/// fallback did not run.
event IntegratorMeasured(
bytes32 indexed tag,
address tokenIn,
address tokenOut,
uint256 amountIn,
FillPath path,
uint256 delivered,
bytes4 swapError,
uint256 swapGas,
bytes4 fallbackError,
uint256 fallbackGas,
uint256 basefee
);
/// @notice Nothing was measured: the frame reverted with `reason`. Everything it did rolled
/// back, so every token is still here.
event MeasureFailed(bytes32 indexed tag, bytes reason);
event AdminNominated(address indexed admin, address indexed pendingAdmin);
event AdminChanged(address indexed previousAdmin, address indexed newAdmin);
event AgentSet(address indexed operator, bool allowed);
event TargetSet(address indexed target, bool allowed);
event MaxAmountInSet(address indexed token, uint256 cap);
modifier onlyAdmin() {
if (msg.sender != admin) revert NotAdmin();
_;
}
modifier onlySelf() {
if (msg.sender != address(this)) revert SelfOnly();
_;
}
modifier nonReentrant() {
uint256 lock;
assembly ("memory-safe") {
lock := tload(_LOCK_SLOT)
}
require(lock == 0, "reentrancy");
assembly ("memory-safe") {
tstore(_LOCK_SLOT, 1)
}
_;
assembly ("memory-safe") {
tstore(_LOCK_SLOT, 0)
}
}
constructor(address settler, address admin_) {
require(settler != address(0) && admin_ != address(0));
SETTLER = settler;
admin = admin_;
emit AdminChanged(address(0), admin_);
}
// ── Administration ───────────────────────────────────────────────────────
function setAgent(address operator, bool allowed) external onlyAdmin {
isAgent[operator] = allowed;
emit AgentSet(operator, allowed);
}
function setTarget(address target, bool allowed) external onlyAdmin {
if (
allowed
&& (target == address(this)
|| target == SETTLER
|| target.code.length == 0
|| maxAmountIn[target] != 0)
) revert BadConfig(target);
isTarget[target] = allowed;
emit TargetSet(target, allowed);
}
function setMaxAmountIn(address token, uint256 cap) external onlyAdmin {
if (cap != 0 && isTarget[token]) revert BadConfig(token);
maxAmountIn[token] = cap;
emit MaxAmountInSet(token, cap);
}
/// @notice Nothing changes until `next` calls `claimAdmin`; `address(0)` cancels.
function nominateAdmin(address next) external onlyAdmin {
pendingAdmin = next;
emit AdminNominated(admin, next);
}
function claimAdmin() external {
if (msg.sender != pendingAdmin) revert NotPendingAdmin();
emit AdminChanged(admin, msg.sender);
admin = msg.sender;
pendingAdmin = address(0);
}
/// @notice Sends `amount` of `token` to `to`; `token == address(0)` sends ETH. A route can
/// leave the input or an intermediate token here (the guide's "your recipient can
/// receive more than `tokenOut`"), and this recovers those too.
function sweep(address token, uint256 amount, address to) external onlyAdmin {
if (token == address(0)) {
(bool ok,) = to.call{ value: amount }("");
require(ok, "eth transfer");
} else {
token.safeTransfer(to, amount);
}
}
// ── measure ──────────────────────────────────────────────────────────────
/// @notice Probe one order and log the result. Never reverts past the agent check and the
/// lock, because the builder asks for a route only about an order that succeeded.
function measure(Params calldata p) external nonReentrant {
if (!isAgent[msg.sender]) revert NotAgent();
try this.runIntegrator(p) returns (IntegratorOutcome memory o) {
emit IntegratorMeasured(
p.tag,
p.tokenIn,
p.tokenOut,
p.amountIn,
o.path,
o.delivered,
o.swapError,
o.swapGas,
o.fallbackError,
o.fallbackGas,
block.basefee
);
} catch (bytes memory reason) {
emit MeasureFailed(p.tag, reason);
}
}
/// @notice The integration guide's call. External so a failure is caught by `measure` and
/// rolls every token and approval back.
function runIntegrator(Params calldata p)
external
onlySelf
returns (IntegratorOutcome memory o)
{
if (!isTarget[p.aggTarget] || !isTarget[p.aggSpender]) {
revert BadTarget();
}
uint256 cap = maxAmountIn[p.tokenIn];
if (p.amountIn == 0 || p.amountIn > cap) revert OverCap(p.amountIn, cap);
if (maxAmountIn[p.tokenOut] == 0) revert BadToken(p.tokenOut);
if (p.aggMinOut == 0 || p.minOut < p.aggMinOut) revert BadFloor(p.minOut, p.aggMinOut);
if (p.aggGasLimit == 0 || p.jitMaxGas == 0) revert BadGas();
uint256 have = p.tokenIn.balanceOf(address(this));
if (have < p.amountIn) revert Underfunded(have, p.amountIn);
(o.delivered, o.swapError, o.swapGas) = _jitLeg(p);
if (o.swapError == bytes4(0)) return o; // ROUTED is 0
(o.delivered, o.fallbackError, o.fallbackGas,) = _aggregatorCall(p);
_approve(p.tokenIn, p.aggSpender, 0);
if (o.fallbackError != bytes4(0)) {
o.path = FillPath.NONE;
return o;
}
if (o.delivered < p.aggMinOut) revert FallbackShort(o.delivered, p.aggMinOut);
o.path = FillPath.FALLBACK;
}
// ── The calls ────────────────────────────────────────────────────────────
/// @dev `swap` with `recipient = this`; the lane is keyed on this contract as `msg.sender`. The
/// settler's return value is ignored: `out` is the measured delta. The approval is zeroed
/// on both paths: a reverted `swap` would otherwise leave it standing.
function _jitLeg(Params calldata p) private returns (uint256 out, bytes4 err, uint256 gasUsed) {
uint256 g = gasleft();
_approve(p.tokenIn, SETTLER, p.amountIn);
uint256 before = p.tokenOut.balanceOf(address(this));
IJITSettler.Request memory req = IJITSettler.Request({
tokenIn: p.tokenIn,
tokenOut: p.tokenOut,
amountIn: p.amountIn,
minOut: p.minOut,
recipient: address(this),
maxGas: p.jitMaxGas
});
try IJITSettler(SETTLER).swap{ gas: p.jitMaxGas }(req) {
out = p.tokenOut.balanceOf(address(this)) - before;
} catch (bytes memory r) {
err = _selectorOf(r);
}
gasUsed = g - gasleft();
_approve(p.tokenIn, SETTLER, 0);
}
/// @dev The aggregator's call: approve, call, `tokenOut` delta. Leaves `aggSpender`'s approval
/// standing: `runIntegrator` zeroes it.
function _aggregatorCall(Params calldata p)
private
returns (uint256 amountOut, bytes4 err, uint256 gasUsed, bytes memory reason)
{
uint256 g = gasleft();
_approve(p.tokenIn, p.aggSpender, p.amountIn);
uint256 before = p.tokenOut.balanceOf(address(this));
bool ok;
(ok, err, reason) = _callBounded(p.aggTarget, p.aggData, p.aggGasLimit);
if (ok) amountOut = p.tokenOut.balanceOf(address(this)) - before;
gasUsed = g - gasleft();
}
// ── Calls and revert data ────────────────────────────────────────────────
/// @dev `approve` that accepts USDT's empty return and, when an allowance is standing,
/// zeroes it first (USDT reverts non-zero to non-zero).
function _approve(address token, address spender, uint256 amount) private {
if (amount != 0 && IAllowance(token).allowance(address(this), spender) != 0) {
_approveRaw(token, spender, 0);
}
_approveRaw(token, spender, amount);
}
function _approveRaw(address token, address spender, uint256 amount) private {
(bool ok, bytes memory ret) =
token.call(abi.encodeWithSelector(IAllowance.approve.selector, spender, amount));
require(ok && (ret.length == 0 || abi.decode(ret, (bool))), "approve failed");
}
/// @dev The aggregator call under `aggGasLimit`: `min(gasleft() - AGG_TAIL_RESERVE,
/// aggGasLimit)`, which EIP-150 may still trim; the cap check compares against what was
/// really forwarded. `used` includes the CALL's own cost, so a near-miss reads as a cap
/// hit, never the reverse.
function _callBounded(address target, bytes calldata data, uint256 aggGasLimit)
private
returns (bool ok, bytes4 err, bytes memory reason)
{
uint256 budget = gasleft();
budget = budget > AGG_TAIL_RESERVE ? budget - AGG_TAIL_RESERVE : 0;
if (aggGasLimit < budget) budget = aggGasLimit;
uint256 used;
uint256 forwarded;
(ok, err, reason, used, forwarded) = _rawCall(target, data, budget);
if (!ok && used + AGG_CAP_EPSILON >= forwarded) err = EXT_CAP_MARK;
}
/// @dev `call(budget, target, data)` keeping at most `MAX_REASON_LEN` bytes of revert data
/// and its selector (`BARE_REVERT_MARK` for fewer than 4 bytes or a zero selector, never
/// a clean zero fill). `forwarded` is what EIP-150 let through:
/// `min(budget, avail - avail / 64)`.
function _rawCall(address target, bytes calldata data, uint256 budget)
private
returns (bool ok, bytes4 err, bytes memory reason, uint256 used, uint256 forwarded)
{
assembly ("memory-safe") {
let ptr := mload(0x40)
calldatacopy(ptr, data.offset, data.length)
let avail := gas()
forwarded := sub(avail, div(avail, 64))
if lt(budget, forwarded) { forwarded := budget }
ok := call(budget, target, 0, ptr, data.length, 0, 0)
used := sub(avail, gas())
let size := returndatasize()
if iszero(ok) {
err := shl(224, 0xffffffff)
if size {
let n := size
if gt(n, MAX_REASON_LEN) { n := MAX_REASON_LEN }
// `reason` at the free pointer (the calldata copy there is dead): length
// word, then the cut data.
reason := ptr
mstore(reason, n)
returndatacopy(add(reason, 32), 0, n)
mstore(0x40, add(add(reason, 32), and(add(n, 31), not(31))))
if gt(size, 3) {
let selector := and(mload(add(reason, 32)), shl(224, 0xffffffff))
if selector { err := selector }
}
}
}
}
}
/// @dev First 4 bytes of `r`; `BARE_REVERT_MARK` for fewer than 4 bytes (no selector) or a
/// zero selector, so a revert never reads as `bytes4(0)`, the clean-fill value.
function _selectorOf(bytes memory r) private pure returns (bytes4 s) {
if (r.length < 4) return BARE_REVERT_MARK;
assembly ("memory-safe") {
s := and(mload(add(r, 32)), shl(224, 0xffffffff))
}
if (s == bytes4(0)) return BARE_REVERT_MARK;
}
}
src/interfaces/IJITSettler.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice What callers integrate (RFC "JITSettler").
interface IJITSettler {
/// @dev RFC: `req` = (tokenIn, tokenOut, amountIn, minOut, recipient, maxGas). `maxGas` is
/// not in the lane key; `maxGas == 0` means no cap. `maxGas` caps the posted
/// `routedEstGas` only; to cap the gas `swap` burns, call `swap{gas: maxGas}(req)`.
struct Request {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 minOut;
address recipient;
uint256 maxGas;
}
/// @dev Indexed on caller, recipient, tokenOut; 8 data words. `routedOut` is the recipient's
/// measured balance change; `routedEstOut` and `routedEstGas` are jit-router's
/// estimates as posted (never rewritten after sim 2), so its accuracy is readable from
/// logs; `simOriginalOut` is the builder's sim 1 of the order without our route. The
/// treasury received `postingChargeOut + feeOut`. Realized gas is the receipt's.
event Settled(
address indexed caller,
address indexed recipient,
address tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 routedEstOut,
uint256 routedOut,
uint256 simOriginalOut,
uint256 routedEstGas,
uint256 postingChargeOut,
uint256 feeOut
);
error NoRoute();
error GasCapExceeded(uint256 maxGas);
error BelowFloor(uint256 recipientOut, uint256 floor);
error BadRecipient();
/// @dev The constructor's `router` does not name this contract as its `SETTLER`.
error RouterNotPaired();
/// @notice Posting aid: the lane a route for `req` sent by `caller` goes to.
function laneFor(address caller, Request calldata req) external pure returns (uint256 lane);
function swap(Request calldata req) external returns (uint256 routedOut);
}
src/libraries/SafeERC20Min.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice Minimal ERC20 surface for `SafeERC20Min`: empty returndata is success (USDT), a
/// returned word is the bool it claims.
interface IERC20Min {
function balanceOf(address) external view returns (uint256);
function transferFrom(address, address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
}
library SafeERC20Min {
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
_call(token, abi.encodeWithSelector(IERC20Min.transferFrom.selector, from, to, amount));
}
function safeTransfer(address token, address to, uint256 amount) internal {
_call(token, abi.encodeWithSelector(IERC20Min.transfer.selector, to, amount));
}
function balanceOf(address token, address who) internal view returns (uint256) {
return IERC20Min(token).balanceOf(who);
}
function _call(address token, bytes memory data) private {
(bool ok, bytes memory ret) = token.call(data);
require(ok && (ret.length == 0 || abi.decode(ret, (bool))), "erc20 call failed");
}
}
src/probe/JitProbe.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { IJITSettler } from "../interfaces/IJITSettler.sol";
import { SafeERC20Min } from "../libraries/SafeERC20Min.sol";
/// @title JitProbe v10 (staging only)
/// @notice Compares a JIT-routed `JITSettler.swap` with an aggregator (0x / KyberSwap) swap of
/// the same order against the SAME pre-state, inside one tx, on a staging builder whose
/// blocks never land. The probe spends a `tokenIn` balance the staging builder injects
/// by state override before it builds; `sweep` recovers what a probe ever holds for real.
/// Not part of the deployment set and not in the bytecode pins (`tools/pin.py`).
///
/// Frames, outermost first:
///
/// measure agents only, reentrancy-locked; SUCCEEDS and emits the outcome
/// └ run SelfOnly; commits and RETURNS the outcome. External so a failure
/// │ (`Underfunded`, a misbehaving token) is caught by `measure` and
/// │ logged as `MeasureFailed` instead of taking the tx down
/// ├ tryAggregator SelfOnly; ALWAYS reverts `LegReport(...)`: the aggregator leg
/// │ is counterfactual, so nothing it does survives
/// └ JIT leg `JITSettler.swap`, COMMITTED
///
/// The aggregator leg runs first and reverts, so the JIT leg prices the very pre-state
/// the aggregator leg saw. A reverting frame can hand a value back only through its
/// revert data, which is what `LegReport` carries.
///
/// Why the JIT leg commits: the builder keeps a pAMM's price update for a block only
/// when the fill's log is in the receipt (rbuilder-prism `simulated_pool.rs`), so a
/// reverted JIT leg would take those makers out of the measured universe.
///
/// Losses are not censored, with no builder flag: the probe sends `minOut = 0` and never
/// falls back, so the builder's sim 1 of the order without our route (`swap` reverts
/// `NoRoute`, caught here) measures `simOriginalOut = 0`. The floor
/// `max(minOut, simOriginalOut)` is 0, jit-router never answers `NOT_BETTER`, and a route
/// worse than the aggregator still fills and is recorded.
///
/// One probe serves several drivers, one agent EOA each, so two `measure`s can land in
/// one block on one injected balance: `Underfunded` checks the balance as this measure
/// finds it, every amount is a balance DELTA around the call that moves it, and every
/// allowance is zero again when `measure` returns, so the next approve is always
/// zero-to-nonzero (USDT).
///
/// `jitOut`/`aggOut` are measured `tokenOut` deltas (0 when the leg reverted); a
/// reverting leg records its 4-byte selector (`NoRoute`, `GasCapExceeded`, `BelowFloor`,
/// ...), `BARE_REVERT_MARK` for a revert with no selector (under 4 bytes of data),
/// `EXT_CAP_MARK` for an aggregator leg that used all of a bounded `aggGasLimit`. The
/// route's posting charge, estimates and sim 1 are in the settler's own `Settled` in the
/// same receipt.
contract JitProbe {
using SafeERC20Min for address;
/// @notice The error value for a leg that reverted with no data (out of gas, bare `revert()`,
/// failed `assert`). Distinct from `bytes4(0)`, which means the leg did not revert.
bytes4 public constant BARE_REVERT_MARK = 0xffffffff;
/// @notice The `aggError` value for a bounded aggregator leg (`aggGasLimit != 0`) that failed
/// having used all of its bound (within `AGG_CAP_EPSILON`), whatever it reverted
/// with: truncated by our bound, never an ordinary aggregator loss.
bytes4 public constant EXT_CAP_MARK = 0xfffffffe;
/// @notice The most revert data the aggregator leg copies: bounded so a target reverting
/// with a huge payload cannot make the probe pay to copy it.
uint256 public constant MAX_REASON_LEN = 164;
/// @dev Gas kept back in `tryAggregator` after a bounded aggregator call, for the post-call
/// `balanceOf` (cold) and the `LegReport` encoding; EIP-150's 1/64 alone may not cover
/// them near the bottom of the budget.
uint256 internal constant AGG_TAIL_RESERVE = 50_000;
/// @dev A failed bounded call that left less than this of what it was forwarded is a cap
/// hit (the callee's last opcodes after its own out-of-gas check).
uint256 internal constant AGG_CAP_EPSILON = 2000;
/// @dev `LegReport` with an empty `reason`: four head words and the length word.
uint256 internal constant LEG_BLOB_LEN = 4 + 5 * 32;
/// @notice One probe. Field ORDER is the ABI: the driver encodes it and pins `measure`'s
/// selector.
/// @param tag The driver's per-send id (`keccak256(quote_id)`), joins sends to outcomes.
/// @param aggSpender Approved for `amountIn` inside the aggregator frame.
/// @param aggTarget,aggData The aggregator's transaction, called verbatim.
/// @param aggGasLimit The most gas the aggregator call may use; 0 = all remaining gas, so an
/// aggregator that burns it all leaves the JIT leg only EIP-150's 1/64 (starved).
/// @param jitMaxGas `Request.maxGas` and the gas forwarded to `swap`; 0 = unbounded, so a
/// route that runs out of gas leaves `run` only the 1/64 EIP-150 holds back.
struct Params {
bytes32 tag;
address tokenIn;
address tokenOut;
uint256 amountIn;
address aggSpender;
address aggTarget;
bytes aggData;
uint256 aggGasLimit;
uint256 jitMaxGas;
}
/// @notice What `run` returns: both legs, measured.
struct Outcome {
uint256 jitOut;
bytes4 jitError;
uint256 jitGas;
uint256 aggOut;
bytes4 aggError;
uint256 aggGas;
}
/// @notice The `JITSettler` under test.
address public immutable SETTLER;
/// @notice Administers agents, ownership and `sweep`; cannot `measure` unless also an agent.
address public admin;
/// @notice Nominated by `nominateAdmin`; becomes `admin` on `claimAdmin`.
address public pendingAdmin;
/// @notice The addresses allowed to call `measure`, one EOA per staging driver.
mapping(address => bool) public isAgent;
// hex of "JitProbeLock": the transient lock slot is named by its contract
uint256 private constant _LOCK_SLOT = 0x4a697450726f62654c6f636b;
error NotAdmin();
error NotPendingAdmin();
error NotAgent();
error SelfOnly();
/// @dev Less than `amountIn` of `tokenIn` here: on staging, the builder's balance injection
/// did not apply to this parent, or earlier measures in the block spent it.
error Underfunded(uint256 have, uint256 need);
/// @dev The aggregator leg's return channel, not a failure. `reason` is its revert data, cut
/// to `MAX_REASON_LEN` bytes.
error LegReport(uint256 amountOut, bytes4 error, uint256 gasUsed, bytes reason);
/// @notice One probe, measured. `jitGas`/`aggGas` cover each leg's approve, call and
/// `tokenOut` delta read.
event Measured(
bytes32 indexed tag,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 jitOut,
bytes4 jitError,
uint256 jitGas,
uint256 aggOut,
bytes4 aggError,
uint256 aggGas,
uint256 basefee
);
/// @notice Nothing was measured: `run` reverted with `reason` (`Underfunded`, a bad token).
event MeasureFailed(bytes32 indexed tag, bytes reason);
event AdminNominated(address indexed admin, address indexed pendingAdmin);
event AdminChanged(address indexed previousAdmin, address indexed newAdmin);
event AgentSet(address indexed operator, bool allowed);
modifier onlyAdmin() {
if (msg.sender != admin) revert NotAdmin();
_;
}
modifier onlySelf() {
if (msg.sender != address(this)) revert SelfOnly();
_;
}
modifier nonReentrant() {
uint256 lock;
assembly ("memory-safe") {
lock := tload(_LOCK_SLOT)
}
require(lock == 0, "reentrancy");
assembly ("memory-safe") {
tstore(_LOCK_SLOT, 1)
}
_;
assembly ("memory-safe") {
tstore(_LOCK_SLOT, 0)
}
}
constructor(address settler, address admin_) {
require(settler != address(0) && admin_ != address(0));
SETTLER = settler;
admin = admin_;
emit AdminChanged(address(0), admin_);
}
// ── Administration ───────────────────────────────────────────────────────
function setAgent(address operator, bool allowed) external onlyAdmin {
isAgent[operator] = allowed;
emit AgentSet(operator, allowed);
}
/// @notice Nothing changes until `next` calls `claimAdmin`; `address(0)` cancels.
function nominateAdmin(address next) external onlyAdmin {
pendingAdmin = next;
emit AdminNominated(admin, next);
}
function claimAdmin() external {
if (msg.sender != pendingAdmin) revert NotPendingAdmin();
emit AdminChanged(admin, msg.sender);
admin = msg.sender;
pendingAdmin = address(0);
}
/// @notice Sends `amount` of `token` to `to`; `token == address(0)` sends ETH. On staging the
/// probe's balances are the builder's injection and vanish with the block; a probe
/// that ever ran in a landed block would hold real tokens.
function sweep(address token, uint256 amount, address to) external onlyAdmin {
if (token == address(0)) {
(bool ok,) = to.call{ value: amount }("");
require(ok, "eth transfer");
} else {
token.safeTransfer(to, amount);
}
}
// ── measure ──────────────────────────────────────────────────────────────
/// @notice Probe one order and log the result. Never reverts past the agent check and the
/// lock: the experiment is the log, so every path emits `Measured` or
/// `MeasureFailed`.
function measure(Params calldata p) external nonReentrant {
if (!isAgent[msg.sender]) revert NotAgent();
try this.run(p) returns (Outcome memory o) {
emit Measured(
p.tag,
p.tokenIn,
p.tokenOut,
p.amountIn,
o.jitOut,
o.jitError,
o.jitGas,
o.aggOut,
o.aggError,
o.aggGas,
block.basefee
);
} catch (bytes memory reason) {
emit MeasureFailed(p.tag, reason);
}
}
/// @notice Both legs: the aggregator's reverted, then the JIT leg committed.
/// @dev `swap` with `minOut = 0`, `recipient = this`, `maxGas = jitMaxGas`; the lane is keyed
/// on this contract as `msg.sender`. The settler's return value is ignored: `jitOut` is
/// the measured delta. `jitGas` is read before the approval is zeroed (bookkeeping
/// only because this frame commits). The approval is zeroed on both paths: a reverted
/// `swap` would otherwise leave it standing past the tx.
function run(Params calldata p) external onlySelf returns (Outcome memory o) {
uint256 have = p.tokenIn.balanceOf(address(this));
if (have < p.amountIn) revert Underfunded(have, p.amountIn);
(o.aggOut, o.aggError, o.aggGas) = _aggregatorLeg(p);
uint256 g = gasleft();
_approve(p.tokenIn, SETTLER, p.amountIn);
uint256 before = p.tokenOut.balanceOf(address(this));
IJITSettler.Request memory req = IJITSettler.Request({
tokenIn: p.tokenIn,
tokenOut: p.tokenOut,
amountIn: p.amountIn,
minOut: 0,
recipient: address(this),
maxGas: p.jitMaxGas
});
try IJITSettler(SETTLER).swap{ gas: p.jitMaxGas == 0 ? gasleft() : p.jitMaxGas }(req) {
o.jitOut = p.tokenOut.balanceOf(address(this)) - before;
} catch (bytes memory r) {
o.jitError = _selectorOf(r);
}
o.jitGas = g - gasleft();
_approve(p.tokenIn, SETTLER, 0);
}
/// @dev `tryAggregator` in its own frame, recovered from its `LegReport`. Anything else is
/// the frame itself failing (out of gas, a bad `tokenOut`): a zero fill with whatever
/// selector came back.
function _aggregatorLeg(Params calldata p)
internal
returns (uint256 amountOut, bytes4 err, uint256 gasUsed)
{
try this.tryAggregator(p) { }
catch (bytes memory r) {
if (_selectorOf(r) == LegReport.selector && r.length >= LEG_BLOB_LEN) {
assembly ("memory-safe") {
// `LegReport`'s head after the selector: amountOut, error, gasUsed.
amountOut := mload(add(r, 36))
err := and(mload(add(r, 68)), shl(224, 0xffffffff))
gasUsed := mload(add(r, 100))
}
return (amountOut, err, gasUsed);
}
return (0, _selectorOf(r), 0);
}
}
/// @notice The aggregator's transaction, replayed verbatim. ALWAYS reverts with
/// `LegReport`, so nothing it does survives: not the approval, not a balance change,
/// not anything `aggTarget` writes. That revert, not an empty balance, is what makes
/// an arbitrary target safe to call while the probe holds `tokenIn`.
function tryAggregator(Params calldata p) external onlySelf {
uint256 g = gasleft();
_approve(p.tokenIn, p.aggSpender, p.amountIn);
uint256 before = p.tokenOut.balanceOf(address(this));
bool ok;
bytes4 err;
bytes memory reason;
if (p.aggGasLimit == 0) {
(ok, err, reason,,) = _rawCall(p.aggTarget, p.aggData, gasleft());
} else {
(ok, err, reason) = _callBounded(p.aggTarget, p.aggData, p.aggGasLimit);
}
uint256 amountOut;
if (ok) amountOut = p.tokenOut.balanceOf(address(this)) - before;
revert LegReport(amountOut, err, g - gasleft(), reason);
}
// ── Calls and revert data ────────────────────────────────────────────────
/// @dev `approve` that accepts USDT's empty return and, when an allowance is standing,
/// zeroes it first (USDT reverts non-zero to non-zero).
function _approve(address token, address spender, uint256 amount) private {
if (amount != 0 && IAllowance(token).allowance(address(this), spender) != 0) {
_approveRaw(token, spender, 0);
}
_approveRaw(token, spender, amount);
}
function _approveRaw(address token, address spender, uint256 amount) private {
(bool ok, bytes memory ret) =
token.call(abi.encodeWithSelector(IAllowance.approve.selector, spender, amount));
require(ok && (ret.length == 0 || abi.decode(ret, (bool))), "approve failed");
}
/// @dev The aggregator call under `aggGasLimit`: `min(gasleft() - AGG_TAIL_RESERVE,
/// aggGasLimit)`, which EIP-150 may still trim; the cap check compares against what was
/// really forwarded. `used` includes the CALL's own cost, so a near-miss reads as a cap
/// hit, never the reverse.
function _callBounded(address target, bytes calldata data, uint256 aggGasLimit)
private
returns (bool ok, bytes4 err, bytes memory reason)
{
uint256 budget = gasleft();
budget = budget > AGG_TAIL_RESERVE ? budget - AGG_TAIL_RESERVE : 0;
if (aggGasLimit < budget) budget = aggGasLimit;
uint256 used;
uint256 forwarded;
(ok, err, reason, used, forwarded) = _rawCall(target, data, budget);
if (!ok && used + AGG_CAP_EPSILON >= forwarded) err = EXT_CAP_MARK;
}
/// @dev `call(budget, target, data)` keeping at most `MAX_REASON_LEN` bytes of revert data
/// and its selector (`BARE_REVERT_MARK` for fewer than 4 bytes: no selector, never a
/// clean zero fill). `forwarded` is what EIP-150 let through:
/// `min(budget, avail - avail / 64)`.
function _rawCall(address target, bytes calldata data, uint256 budget)
private
returns (bool ok, bytes4 err, bytes memory reason, uint256 used, uint256 forwarded)
{
assembly ("memory-safe") {
let ptr := mload(0x40)
calldatacopy(ptr, data.offset, data.length)
let avail := gas()
forwarded := sub(avail, div(avail, 64))
if lt(budget, forwarded) { forwarded := budget }
ok := call(budget, target, 0, ptr, data.length, 0, 0)
used := sub(avail, gas())
let size := returndatasize()
if iszero(ok) {
err := shl(224, 0xffffffff)
if size {
let n := size
if gt(n, MAX_REASON_LEN) { n := MAX_REASON_LEN }
// `reason` at the free pointer (the calldata copy there is dead): length
// word, then the cut data.
reason := ptr
mstore(reason, n)
returndatacopy(add(reason, 32), 0, n)
mstore(0x40, add(add(reason, 32), and(add(n, 31), not(31))))
if gt(size, 3) {
err := and(mload(add(reason, 32)), shl(224, 0xffffffff))
}
}
}
}
}
/// @dev First 4 bytes of `r`; `BARE_REVERT_MARK` for fewer than 4 bytes (no selector), so
/// a short revert never reads as `bytes4(0)`, the clean-fill value.
function _selectorOf(bytes memory r) private pure returns (bytes4 s) {
if (r.length < 4) return BARE_REVERT_MARK;
assembly ("memory-safe") {
s := and(mload(add(r, 32)), shl(224, 0xffffffff))
}
}
}
interface IAllowance {
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 1000,
"enabled": true
},
"evmVersion": "osaka",
"remappings": [
"forge-std/=lib/forge-std/src/",
"priority-update-registry/=vendor/priority-update-registry/src/",
"solady/=lib/priority-update-registry/lib/solady/src/",
"@openzeppelin/=lib/priority-update-registry/lib/openzeppelin-contracts/",
"erc4626-tests/=lib/priority-update-registry/lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/priority-update-registry/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/priority-update-registry/lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.