DOCS / 07

Contracts

The Router, the Executor, the Orders contract, its price reference and its views, their addresses, the swap and order interfaces, the fee model, the owner's powers and the security properties the contracts enforce.

Updated · Markdown version

Tirio's on-chain side is five contracts. The Router is the fixed entry point that users give their allowance to; it takes the fees and enforces the minimum output. The Executor runs the route the API built and can be called only by the Router. The Orders contract holds the tokens of open limit, stop and DCA orders and fills them through the Router. The Oracle is the independent price reference that stop and DCA fills are checked against, and OrdersLens serves the read-only views of the orders.

Addresses

ContractAddressRole
Router0x9B1c368F5d33a8D051587c7576b150132680ADC0Entry point that allowances are given to, fee vault
Executor0xb4406b302959c4BCca1E31dF7fD0EB0e143600B2Runs swap routes, callable only by the Router
Orders0x06360a557290f64aeC55B7a06b788eD8723e71f9Escrow for limit, stop and DCA orders, filled through the Router
Oracle0x4737C003D59667A0ef0B9eC7bdA4d34959eE2c72Price reference for stop and DCA fills: Chainlink feeds or a 30-minute pool TWAP
OrdersLens0x844ff0401646A42A868d7029eB5dC847796CA686Read-only views of the Orders contract
Create3Factory0x02944AFeAD4d9c7A09c6D9E56B9027B84B6F242FCREATE3 deployer that gives the contracts the same address on every chain they are deployed to

All of these contracts are deployed on BNB Chain only. Their addresses were chosen to be the same on any other chain they are deployed to later: the factory sits at the same CREATE2 address everywhere (Arachnid deployer, salt 0), and a CREATE3 address depends only on the factory, the deployer and the salt, not on the contract's code. On other chains these addresses are empty today.

ChainStatus
BNB Chain (56)Live. Router: protocol fee 0, Router share of partner fees 10 %, partner share of kept positive slippage 20 %. Orders: order fee 10 bps, 3 bps between stablecoins.
Robinhood Chain (4663)Not deployed. Planned, with no launch date.

The app carries the Router and Orders addresses as fixed constants and verifies every transaction against them. The API also reports them in /health (router, orders); the app only compares those with its own, and if the API ever reports a different contract it pauses swaps or orders instead of following it.

Router

struct SwapParams {
    address tokenIn;
    address tokenOut;
    uint256 amountIn;
    uint256 minOut;
    uint256 expectedOut;
    address recipient;
    address inputTo;
    uint256 deadline;
    address partner;
    uint16 partnerFeeBps;
    uint8 flags;
}
 
function swap(SwapParams calldata p, bytes calldata route, bytes calldata permit)
    external payable returns (uint256 amountOut, uint256 amountInUsed);
  • Amount. amountIn is the most the Router may take from the payer: the whole amount for an exact-in swap, a ceiling for an exact-out route that pulls only what its output costs. amountInUsed is what was actually charged.
  • Fees. The protocol fee (feeBps, 0 today and 3 bps at deployment, hard cap 100 bps, 0 for a payer marked fee-exempt) and the optional partner fee (partnerFeeBps, at most 1000 bps, paid to partner in the same transaction minus the owner-set partnerShareBps cut, 10% at deployment and at most 20%) are charged on the input actually used. flags can move either fee to the output (PROTOCOL_FEE_ON_OUTPUT = 2, PARTNER_FEE_ON_OUTPUT = 4), which requires SETTLE_OUTPUT = 1. When the protocol fee is above 0, the API puts it on the output when the output token is a hub token without transfer tax and the quote is exact-in; otherwise it stays on the input. The partner fee follows feeToken, or the protocol fee's side when feeToken is not given, which is the input while the protocol fee is 0. The tirio.io app charges its 3 bps Tirio fee as a partner fee to the treasury.
  • ERC-20 input. The Router moves only the payer's tokenIn, never more than amountIn and only while that swap runs. inputTo belongs to the route the API builds, so pass it exactly as the quote returns it. After the route the fees are pulled from the payer.
  • Recipient. recipient must not be the zero address (ZeroAddress).
  • Native input. msg.value must equal amountIn; the net amount is forwarded to the Executor and whatever the route leaves is refunded to the payer.
  • Output. Without SETTLE_OUTPUT the output goes straight to recipient and minOut is checked against the recipient's balance change (a drop counts as zero). With SETTLE_OUTPUT the route pays the Router, output-side fees are taken from what arrived, anything above expectedOut is kept as surplus up to 1% of expectedOut (the partner receives surplusPartnerBps of it, 20 % today), and the rest is sent to recipient, the native coin by call. Less than minOut reverts with InsufficientOutput. The API sets SETTLE_OUTPUT and expectedOut to the quoted output on every exact-in quote whose output token has no transfer tax, so positive slippage on those swaps is capped and kept as described.
  • Permit. permit is empty for a classic allowance, 0x01 plus an EIP-2612 permit (value ‖ deadline ‖ r ‖ s ‖ v) that the Router tries before pulling, or 0x02 plus a Permit2 PermitSingle with an optional signature after which every pull goes through Permit2.transferFrom. The API builds the bytes and tells the app where the signature goes.
  • Deadline. block.timestamp > deadline reverts with Expired. tokenIn == tokenOut reverts with SameToken.
  • A transient reentrancy lock guards the entry point. Every swap emits Swap(sender, partner, tokenIn, tokenOut, amountIn, amountOut, recipient, protocolTake, partnerTake, surplus).
  • Owner functions. setExecutor, setFeeBps, setShares(partnerShareBps, surplusPartnerBps), setFeeExempt, and withdraw(tokens[], to) for accumulated fees (for ERC-20 fees one unit of dust stays behind).

Executor

execute(bytes route) runs the route the API built for a swap, and only the Router can call it. The Executor holds no funds and no allowances between transactions, and every swap ends with its balance at zero. The owner can replace it through the Router's setExecutor. The route format belongs to Tirio and may change with a new Executor, so integrators pass the route bytes of a quote unchanged.

Pool fees are never hard-coded in the contracts: the API reads the current fee from each pool, and concentrated-liquidity pools apply their fee themselves.

Orders

The Orders contract holds the tokens of open orders and fills them through the Router, whose address is fixed in the contract; the Router exempts it from the swap fee. It needs no signatures and no off-chain state: an order is written on chain when it is placed, and everything the app shows about it is read back from the contract. It has no proxy and no delegatecall, so its code cannot change. How the order types behave for a user is described in Orders.

enum Kind { Limit, Stop, DCA }
 
struct Place {
    address tokenIn;
    address tokenOut;
    uint256 amountIn;
    uint256 minOut;
    uint256 maxOut;
    uint256 triggerOut;
    uint256 minFill;
    uint32 chunks;
    uint40 interval;
    uint40 expiry;
    bool startNow;
    address partner;
    uint16 partnerFeeBps;
    Kind kind;
    bool book;
    address pool;
    uint16 deviationBps;
}
 
function place(Place calldata p, bytes calldata permit) external payable returns (uint256 id);
function cancel(uint256 id) external;
function cancelAll(uint256[] calldata ids) external;
function pause(uint256 id) external;
function resume(uint256 id) external;
function update(uint256 id, uint32 chunks, uint40 interval, uint256 minOut, uint256 maxOut) external;
function expire(uint256 id) external;
function claim(address token) external returns (uint256 amount);
function fill(uint256 id, uint256 fillIn, uint256 minOut, uint8 leg, bytes calldata route)
    external returns (uint256 out, uint256 used);
  • Placing. place takes amountIn of tokenIn into the contract before the order is written: the native coin as msg.value, an ERC-20 through a classic allowance, an EIP-2612 permit (0x01 plus value ‖ deadline ‖ r ‖ s ‖ v) or Permit2 (0x02 plus a PermitSingle and an optional signature), the Router's permit formats with Orders as the spender. A token that delivers less than amountIn is refused (FeeOnTransfer). Every kind needs a non-zero minOut; the expiry is at most 365 days away; a limit order has no maxOut or triggerOut; a stop needs minOut at or below triggerOut and a take-profit maxOut above it; a DCA order needs at least two chunks at least 60 seconds apart; only a limit order can set book.
  • Price reference. A stop or DCA order carries pool, the pool the Oracle prices the pair with (zero when the pair has Chainlink feeds), and deviationBps, the order's tolerance against that price, at most 1000 (DeviationTooHigh). The API fills both in: 500 for a stop and 300 for a DCA order unless the request sets deviationBps. Placing a stop or DCA order asks the Oracle for a price once, so a pair it cannot price cannot be placed. A limit order carries neither.
  • Minimums. minimums(token) is the smallest order, about $5 worth, per token. An order below the minimum of its tokenIn (for DCA, each chunk amountIn / chunks), a non-zero minFill below it, and a book order for a token without a minimum revert with BelowMinimum. A partial fill, take or give must leave nothing or at least minFill (BadFill).
  • The floor is net. minOut is the output the maker must receive for the whole amountIn, after the order fee and the partner fee, enforced in proportion to every fill: out − fee − partnerFee ≥ ceil(minOut × fillIn / amountIn). Everything above the floor goes to the maker, except on a book trade, where the taker pays exactly the limit.
  • Filling. fill debits the order first, then calls Router.swap with Orders as payer and recipient, a minOut no lower than the floor grossed up by the fees, and SETTLE_OUTPUT, so the output is measured on the Router. Input the route leaves unused returns to the order, and a fill that uses none reverts (BadFill). At the end the contract must hold at least what it owes in both tokens (Insolvent), so a token that delivers less than it reports can never be paid out of another order. leg 0 is the floor of any order; leg 1 is the take-profit leg of a stop, whose floor is maxOut. Both legs spend the same escrow.
  • Price-checked fills. On a stop leg and on every DCA chunk the contract reads market = Oracle.quote(tokenIn, tokenOut, amountIn, pool). A stop leg fills only when market is at or below triggerOut (NotTriggered), and the floor of both becomes the higher of minOut and the Oracle's output after the order's fees less deviationBps. Take-profit legs and limit orders do not use the Oracle.
  • DCA. A chunk is remainingIn / (chunks − filledChunks), the last one takes what remains, and it is due at nextFillAt. After a fill the next one is due at nextFillAt + interval, or now + interval when that time has already passed. maxOut bounds a chunk's gross output (PriceTooHigh). The maker can pause, resume and update the chunks left, the interval and both bounds.
  • The order book. A limit order placed with book set can also be taken inside a Tirio swap, at exactly its limit price and never below it (PriceTooLow). Only the Router's current Executor can take a listed order, only while the order is open, and never the order that is being filled.
  • Fees. feeOf(tokenIn, tokenOut) is the pair's override from setPairFee when one is set (3 bps between stablecoins at launch), otherwise feeBps (10 bps at deployment, at most 100), taken from the output of every fill. A partner fee comes on top, of which protocolShareBps (10 % at deployment, at most 20 %) stays with the protocol. Protocol fees are booked in accrued(token).
  • Payouts never revert. Payments to makers and partners and refunds are sent without letting a failure revert the fill, cancel or expiry: the native coin with 50 000 gas and no return data copied, an ERC-20 with a checked call. What cannot be delivered is booked in claimable(account, token) with Owed(account, token, amount), and claim(token) pays it out to that account.
  • Cancel and expiry. cancel(id) and cancelAll(ids) belong to the maker (cancelAll skips closed orders and reverts on someone else's); expire(id) may be called by anyone after the expiry. Both return what remains to the maker.
  • History on chain. Every order keeps its status (Open, Filled, Cancelled, Expired), filledIn and receivedOut, so one read gives what was filled, what the maker received and the average price.
  • History on chain also keeps each order's pool and deviationBps: an Order is 25 ABI words.
  • Views. Orders answers feeOf(tokenIn, tokenOut), claimable(account, token), minimums(token), liabilities(token), accrued(token), oracle(), keeper(), lastPing(), grace(), feeBps(), protocolShareBps() and accepting(). The order lists and the orders themselves are read from OrdersLens (below).
  • Events. Placed(id, maker) (read the order with OrdersLens.orders(id)), Filled(id, filler, fillIn, out, fee, partnerTake, leg, viaBook), Cancelled(id, refund), Expired(id, refund), Paused(id, paused), Updated(id, chunks, interval, minOut, maxOut), Owed(account, token, amount), Claimed(account, token, amount), and for owner actions KeeperSet, FeeSet, PairFeeSet, ProtocolShareSet, GraceSet, AcceptingSet, OracleSet, MinimumSet, OwnerSet and Withdrawn.

Keeper and owner

  • Keeper. One address set by the owner may fill any order and call ping(), which it does every five minutes. Once lastPing is older than grace (15 minutes at deployment), anyone may fill limit orders and take-profit legs; stop legs and DCA chunks always stay with the keeper. The keeper has no other power.
  • Owner functions. setKeeper (restarts the grace period), setFeeBps and setPairFee (at most 100 bps), setProtocolShareBps (at most 20 %), setGrace, setOracle, setMinimum, setAccepting (stops new orders only: open orders still fill, cancel and expire) and withdraw(tokens, to) (exactly the accrued fees).
  • What the owner cannot do. Move escrowed tokens or claimable balances, change or close someone's order, block a cancel or an expiry, or change the contract's code or its Router. A fee change applies to later fills of open orders, but because the floor is net of fees the maker still receives at least the price of the order. The worst a malicious keeper, or an owner who installs one, can do is fill orders at their floors, which on stop legs and DCA chunks include the price check.
  • Deployment. The contract accepts orders once the owner opens it with setAccepting(true), the last step of the deployment after the Router's fee exemption, the keeper, the stablecoin pair fees and the token minimums. The keeper is 0xDd301C136A83Bb0d62F74272f4d3e57B278A0D13.

Oracle

quote(tokenIn, tokenOut, amountIn, pool) returns what amountIn is worth in tokenOut at the reference price, or reverts. When both tokens have a Chainlink USD feed it uses the feeds and refuses a stale or non-positive answer (StalePrice, BadPrice). Otherwise it uses the 30-minute TWAP of the PancakeSwap V3 or Uniswap V3 pool given in pool, which must belong to an allowed factory, match the pair (BadPool) and keep at least 100 observations (FewObservations). Without feeds and without a pool it reverts with NoOracle. It is a view with no owner and no state that can change.

OrdersLens

A stateless contract that reads the Orders contract's storage and returns the same views as before: orders(id), lens(ids), openCount(), openAt(start, n), bookCount(tokenIn, tokenOut), bookAt(tokenIn, tokenOut, start, n), bookOf(tokenIn, tokenOut), makerCount(maker), makerAt(maker, start, n) and ordersOf(maker), plus ORDERS(). The app reads the orders table from it when the API does not answer.

Security properties

  • The Router can move only the payer's tokenIn, only up to amountIn and only inside a swap the payer sent. There is no other path to a user's allowance. An EIP-2612 permit signed for the Router writes an allowance for that swap's amount and is used up by it. A Permit2 PermitSingle grants Permit2 an allowance for the Router that a swap does not use up (the API asks for the uint160 maximum with a 30-day expiry), so it stays valid until it expires or you revoke it in Permit2 or revoke the token's approval to Permit2.
  • The output must reach the recipient: minOut is enforced on the recipient's actual balance change, not on a number the route reports.
  • Administrative functions are onlyOwner and limited to the fee (at most 100 bps), the partner and surplus shares (at most 20% and 100%), fee exemptions, the Executor address, the owner address and withdrawing accumulated fees.
  • The Router is not upgradeable: no proxy, no delegatecall, no way to change its code.
  • The Executor is replaceable by the owner through setExecutor. A replaced Executor still runs only inside swaps users signed, can pull at most that swap's budget of tokenIn, and the Router still enforces the user's minOut and deadline.
  • Every swap is atomic: it settles completely or reverts completely.
  • The Orders contract takes tokens only from the wallet that calls place, and only that order's amountIn. It moves an order's tokens only to fill it at no less than its net floor, to refund the maker on a cancel or an expiry, or to pay a claimable balance to the account it is owed to. After every fill it must still hold its open escrow, accrued fees and claimable balances in both tokens.
  • A transient reentrancy lock guards placing, cancelling, updating, expiring, filling and claiming; book trades cannot nest and are refused while any of those runs, except inside a fill's Router call. An order leaves the open lists before anyone is paid, and a book trade cannot take the order that is being filled.
  • Tokens that take a transfer tax cannot be placed, and a fill whose output token delivers less than it reports reverts. A token that reports a failed transfer while still moving the tokens is outside what Orders supports: for such a token a refund can be paid twice, at the expense of other orders in the same token. Such tokens are rare and the risk stays within that token's orders; take care with unlisted tokens you paste.

Testing

The contracts are covered by 477 tests: 366 local unit, fuzz and invariant tests (fees on either side, partner fees, the capped surplus, permits through EIP-2612 and Permit2, the Oracle's price paths, minimums and price-checked fills), 71 Router fork tests against real pools on four chains, and 40 fork tests on BNB Chain that run orders and swaps with real tokens, real Chainlink feeds and a real PancakeSwap V3 TWAP. Coverage of the contract sources is measured with forge coverage before every release: the Router and Orders at more than 98 % of lines and every function, OrdersLens at 100 %.

The Orders invariant suite drives placements, cancels, expiries, fills, book trades, claims, updates, fee changes and withdrawals over several tokens with a reentrant maker, prices stop and DCA fills through the Oracle, and checks after every call that the contract holds exactly its open escrow, accrued fees and claimable balances.