Integrate JIT routing
Your contract asks JITSettler for a route, fills through it if there is one, and runs your own route if not. This page shows two ways to do that, and a callback variant. Read the overview first.
Before you start
You do not need permission to integrate. Any contract can call the settler, and the builder tries to route every call it receives. It may skip small swaps, and under heavy load it prioritizes large swaps. The contracts have not been audited.
- Check that the swap fits what this version supports.
- Make sure the builder receives the transaction. If you control submission, send it to the BuilderNet RPC at
https://rpc.buildernet.org. If you do not, the builder routes the swap only when the transaction reaches it by another path, such as the public mempool. - Approve the settler for each
tokenIn. The settler transfers onlyamountIn, and only when your contract callsswap.
The settler's functions
Every function takes the same request:
struct Request {
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 amountOutMin;
address recipient;
}
| Function | What it does |
|---|---|
peek(req) | Returns the address that posted the route for this block (the poster), or 0 if there is no route. |
swap(req, callback) | Fills req through the posted route and returns what recipient received. Reverts if there is no route or the route fails. With callback set, it first calls routeAvailable(poster) on your contract. |
reportDefault(req, amountOut) | Records what your own route paid. See Report your route. |
A fill transfers amountIn of tokenIn from your contract and pays tokenOut to recipient. If swap reverts, no tokens are transferred.
Choose an integration
| Integration | What your contract does | Sample function |
|---|---|---|
| Efficient | Runs routes only from a builder it trusts, and trusts that builder to post only routes that beat yours. | tradeEfficient |
| Safe | Runs routes only from a builder it trusts, and also checks onchain that each fill beats your route. | tradeSafe |
When no route is posted, both add one call to the settler before your route, and the report after it. When a route is posted, both integrations check who posted it. The efficient integration then fills. The safe integration first runs your route in a trial to measure it, and accepts the fill only if it pays more. If the fill loses, your route runs a second time.
Both read the poster with peek. If you prefer that the settler calls your contract, use the safe integration with a callback.
Both, and their callback variants, are in one sample contract, JitIntegration.sol, with tests. The sections below show excerpts from it, without the helper functions. They share this state:
abstract contract JitIntegration {
// Keep both settable: a new settler is a new address, and a new builder is a new poster.
IJITSettler public jit;
mapping(address => bool) public trustedPoster;
// The safe integrations cap the gas that a route can use.
uint256 public routeGas = 1_500_000;
/// Your own route. Swaps `req.amountIn` and pays `req.tokenOut` to `req.recipient`.
function _yourRoute(IJITSettler.Request memory req) internal virtual;
// Runs your route and returns what it paid. The caller reports it with `reportDefault`.
function _runYourRoute(IJITSettler.Request memory req) private returns (uint256 out) {
uint256 before = IERC20(req.tokenOut).balanceOf(req.recipient);
_yourRoute(req);
out = IERC20(req.tokenOut).balanceOf(req.recipient) - before;
require(out >= req.amountOutMin, "below minimum");
}
}
IJITSettler is in the reference. The sample has no access control. Add it, with functions that set jit, trustedPoster and routeGas. Never mark the zero address as trusted, because peek returns it when no route is posted.
Every integration ends the same way when no route fills: it runs your route and calls reportDefault with what the route paid. The settler then emits JITDefaultV1, and the builder uses it as the amount that a route has to beat. See Report your route.
A route runs code that you did not choose, in the middle of your transaction. Guard every function of your contract that an outside caller can use to move tokens or change state. The sample's nonReentrant modifier does this for the four trade functions.
Efficient
function tradeEfficient(IJITSettler.Request calldata req) external nonReentrant returns (uint256) {
// Always make this call. With no route it returns 0, and the builder finds your swap from it.
if (trustedPoster[jit.peek(req)]) {
try jit.swap(req, false) returns (uint256 got) {
return got;
} catch {
// The route failed, and no tokens were transferred.
}
}
uint256 out = _runYourRoute(req);
jit.reportDefault(req, out); // emits JITDefaultV1: what a route has to beat
return out;
}
The contract checks only that a fill pays at least req.amountOutMin. It does not check that the fill pays more than your route. The builder guarantees that.
Safe
When a trusted poster's route is posted, the contract first measures what your route would pay. It runs your route in a call that always reverts, so the trial changes no state. The contract then accepts the fill only if it pays more than that amount. The contract measures the improvement itself, so it does not rely on the builder to post only routes that beat yours.
function tradeSafe(IJITSettler.Request calldata req) external nonReentrant returns (uint256) {
if (trustedPoster[jit.peek(req)]) {
(bool ok, uint256 yours) = _measureYourRoute(req);
if (ok) {
// The gas cap keeps enough gas for your route if this route uses all of its gas.
try this.swapChecked{gas: routeGas}(req, yours) returns (uint256 got) {
return got;
} catch {
// The route failed or did not beat your route. The fill is undone.
}
}
}
uint256 out = _runYourRoute(req);
jit.reportDefault(req, out); // emits JITDefaultV1: what a route has to beat
return out;
}
/// A revert here undoes the fill and leaves the rest of the transaction intact.
function swapChecked(IJITSettler.Request calldata req, uint256 yours)
external
onlySelf
returns (uint256 got)
{
got = jit.swap(req, false);
require(got > yours, "not better");
}
Two limits apply:
- The gas cap.
routeGascaps the gas that a route can use, so a faulty route cannot use the gas that your own route needs. Set the transaction's gas limit to cover the trial, the cap and your route. - The check compares against your route in this transaction. A transaction placed before yours can move prices, so that your route measures low. Your swap has the same exposure without JIT routing, and
amountOutMinis your limit in both cases.
_measureYourRoute and its two helper functions are in the sample contract. The helpers and swapChecked accept calls only from your contract itself, during a trade (onlySelf). Do not put the reentrancy guard on them: tradeSafe already holds it.
Your own route must never call your contract with calldata that someone else chose. That call comes from your contract, so onlySelf accepts it.
Safe with callback
Call swap(req, true) and skip peek. With no route posted, swap reverts with NoRoute and does not call your contract. With a route posted, the settler first calls routeAvailable(poster) on your contract. Return the least that recipient must receive, or revert to decline the route.
In this integration, routeAvailable checks the poster, measures your route in a trial, and returns that amount plus 1. The settler then accepts the fill only if it pays more than your route.
function tradeSafeCallback(IJITSettler.Request calldata req) external nonReentrant returns (uint256) {
// routeAvailable gets only the poster, so keep the request for it.
(_tokenIn, _tokenOut, _amountIn) = (req.tokenIn, req.tokenOut, req.amountIn);
(_amountOutMin, _recipient) = (req.amountOutMin, req.recipient);
// Always make this call. With no route it reverts with NoRoute, and the builder finds your
// swap from it. The gas cap also covers the trial of your route in routeAvailable.
try jit.swap{gas: routeGas}(req, true) returns (uint256 got) {
return got;
} catch {
// No route was posted, your contract declined it, or it failed. No tokens were transferred.
}
uint256 out = _runYourRoute(req);
jit.reportDefault(req, out); // emits JITDefaultV1: what a route has to beat
return out;
}
function routeAvailable(address poster) external returns (uint256 floor) {
require(msg.sender == address(jit) && _inTrade, "not in a trade");
require(trustedPoster[poster], "untrusted poster"); // a revert declines the route
(bool ok, uint256 yours) = _measureYourRoute(
IJITSettler.Request(_tokenIn, _tokenOut, _amountIn, _amountOutMin, _recipient)
);
require(ok, "your route failed");
return yours + 1; // the fill must pay more than your route
}
_tokenInto_recipientare transient storage variables of the sample contract. They hold the request while the trade runs.- The floor is the larger of
req.amountOutMinand the value you return. The callback can raise the floor but not lower it. routeAvailableruns inside yourtradecall, so it cannot carry the reentrancy guard. Its first line accepts a call only from the settler, and only during a trade.- The trial of your route runs inside the capped
swapcall. Set the cap to the gas you allow for a route plus the gas of your own route. The sample uses the samerouteGasvalue astradeSafe, so here a route gets less gas than the cap. - For an efficient integration with a callback, leave out the trial and the gas cap, and return 0 from
routeAvailable. The floor then stays atreq.amountOutMin. The sample'stradeEfficientCallbackdoes this. The sample contract shares onerouteAvailablebetween the two, so it has one more branch.
Without new code
If you cannot deploy new code, you can still integrate if your contract can make a generic external call and continue after it reverts. Call swap(req, false) with a gas cap, and run your route only if the call reverts.
This integration checks neither the poster nor the builder's coinbase. There is then no guarantee about what kind of route is posted, so your guarantees are limited to what you check onchain. The JITSettler enforces only amountOutMin. Your contract can still compare the fill with its own route onchain.
Check the poster
Anyone can post a route to the settler. The poster is the address that posted it, and nobody can post in another address's name. Run a route only if its poster is a builder you trust. Both sample integrations check this.
BuilderNet posts from 0x4a1f5Ac5652F8046dC1088095d34a21c526cE548 (reference).
Within the contract's limits, a route from a poster that you do not check (i.e. from an untrusted builder) can do the following:
| A hostile route can | What you do |
|---|---|
Fill at exactly amountOutMin and keep the rest. | Check the poster. Set amountOutMin to your minimum on every call. |
Use all the gas you forward to swap. | Check the poster. The safe integrations in the sample also cap the call with {gas: cap}. |
| Call back into your contract during the fill. | Guard your contract against reentrancy. |
Report your route
The builder posts a route only if it beats what your own route pays (the baseline). The builder gets the baseline from its simulation of your transaction with no route posted:
- If your transaction calls
reportDefault, the baseline is the reportedamountOut. With more than one report, the builder uses the first one after yourpeekorswapcall. The builder ignores a report of 0, or of less than the request'samountOutMin, and uses rule 2. - If your transaction reports nothing, the baseline is the sum of
tokenOuttransfers torecipientin the transaction. IftokenOutis WETH, native ETH paid torecipientin the transaction counts as well.
We recommend issuing the event, but it is optional. Call reportDefault(req, amountOut) after your route runs, from the contract that called peek or swap, with the same req. The builder ignores a report from any other contract. Report the growth of recipient's tokenOut balance, because that is how the settler measures a fill. The sample measures this in _runYourRoute and reports it in each trade function.
Without a report, two cases distort the baseline:
- Your route takes a fee before it pays
recipient. The builder then counts only whatrecipientreceived, so the baseline is your route's output less your fee. Take your fee afterrecipientis paid, whether the swap filled or your route ran. tokenOutreachesrecipientmore than once in your transaction. Every transfer counts, so the baseline can be too high for any route to beat.
When the builder routes your swap
The builder searches for a route only if all of these hold when it simulates your transaction with no route posted:
- The transaction calls
peekorswapon the settler with the request. - The transaction succeeds through your route.
- The request is the same in the simulation and at execution, and the same in every call to the settler. Fix its five fields in your calldata. A field computed from onchain state, such as your contract's balance or a live quote, can change in between.
- The transaction calls
swapat most once, and the call covers the whole swap. A posted route can fill only oneswapcall. - Your route pays
tokenOuttorecipient.
A failed condition currently does not give an error. The builder posts no route, and your route runs.
Set the request fields
recipient
Set recipient to the account your route pays, usually your contract. A fill pays recipient directly.
To pay out native ETH, set tokenOut to WETH and recipient to your contract, and unwrap after the fill.
amountOutMin
amountOutMin is the least that recipient can receive from a fill. It is the one limit on your output that the contract enforces in every integration.
- Set it to your minimum, the lowest output at which you would let the swap complete.
- Do not set it at your quote. The builder compares a route with what your route pays in the block, which is often less than your quote. With
amountOutMinat your quote, a route that pays less than the quote fails, even when it pays more than your route does in the block. - Do not set it near zero.
If you know your minimum only during execution, use a safe integration or return the minimum from routeAvailable.
Gas
The request has no gas field. A route gets all the gas that the swap call has.
- If you do not cap the call, as in the efficient integrations, you rely on the builder. It posts a route only when your whole transaction succeeds with it, and it fits the route to the gas your transaction has.
- If you cap the call, for example
jit.swap{gas: cap}(req, false), the transaction's gas limit must cover the cap and your own route. The safe integrations cap the call, and they also run your route once more as a trial. Always cap the call if you do not check the poster, as in the integration without new code. A cap below what a good route needs loses fills, so tune it with the table below.
Leave gas for the route in the transaction's gas limit, on top of what your own route needs. A large swap gains from a route split across several pools, and that route needs more gas.
How much to leave is a parameter for you to tune for your own flow. These values are a good starting point, from our simulations of past swaps:
| Swap size | Gas to leave for the route |
|---|---|
| Under $30k | 1,000,000 |
| $30k to $100k | 1,500,000 |
| Over $100k | 2,000,000 |
With less than 500k, most routes do not fit. To tune the value, compare the fills you get at different limits (Monitor fills).
eth_estimateGas simulates your transaction with no route posted. Its estimate can be too low for a transaction that fills through a route.
You pay only for the gas used. If a downstream system ranks your quotes by gas limit, the higher limit lowers your rank.
If you bid for inclusion with gas fees
A JIT route can use less gas than your own route. If you pay the builder through the priority fee, your payment then falls, and the builder may not post the route. This should not affect aggregator flow, which typically pays below the threshold where this is relevant. We recommend users finely tuning block position via priority fees to switch to payments to block.coinbase when invoking the JITSettler. A payment to block.coinbase does not depend on the gas used.
Handle reverts
Run your route on every revert from swap. Do not branch on the revert data, because it can come from the route. You also cannot detect from the revert data that swap ran out of gas, because that revert carries no data.
The settler's own errors are in the reference.
Monitor fills
The settler emits JITRoutedV1 for every fill, indexed by your contract's address, and JITDefaultV1 for every report. The two events carry the same request fields, so you can compare what fills paid with what your route paid. In JITRoutedV1, amountOutMin is the floor that applied, which is higher than the request's if your callback raised it.
Checklist
- The settler is approved for each
tokenIn. - Your contract runs a route only from a poster it trusts.
-
swapis called at most once, insidetry/catch, and your route runs on any revert. - The five request fields are fixed in calldata, and every simulated settler call during block building gets the same request.
- Your route reports what it paid with
reportDefault, or the sum of transfers torecipientis an adequate baseline. - The transaction gas limit leaves gas for a route.
- If you are searching and paying significant bids for position in the block, you pay the builder through
block.coinbase(why). - The settler address and the trusted posters are settable.
- Your contract has its own reentrancy guard.
- The integration passes the sample tests.