Contract API
Generated by
node scripts/gen-contract-api.mjsfrom NatSpec; do not edit by hand.
Every public and external function, event, custom error, struct and enum of the vault, its lens, the order types and the libraries, read from the NatSpec in the Foundry build artifacts. Members appear in source order. Prices are quote per 1 base with 8 decimals; HBAR amounts are tinybar; bps are basis points.
Contents
- OrderVault (contract)
- OrderVaultLens (contract)
- LimitOrderType (contract)
- StopOrderType (contract)
- TrailingStopType (contract)
- IOrderType (interface)
- MarketGuard (library)
- MarketRegistry (library)
- OrderCollection (library)
- Settlement (library)
- SweepMath (library)
- PriceMath (library)
- Shared types (
OrderTypes.sol)
OrderVault
- Source:
packages/foundry/contracts/OrderVault.sol - Inherits
Ownable2Step,ReentrancyGuard - Hedera testnet:
0xc265045c65d0114109072d60b3a60231427a06a9
Limit and stop orders that execute on SaucerSwap V2 with no off-chain keeper.
Each order is an HTS NFT minted by this vault; whoever holds it owns the order. Each market runs one self-rescheduling sweep through the Hedera Schedule Service, and the sweep's cost is split across the orders it checks. Scheduling a call is a fixed network fee, so the next sweep waits as long as the nearest trigger allows. A fill needs the pool's TWAP to agree with Chainlink, so a manipulated or stale market cannot drain an order.
Public variables
| Name | Declaration | Description |
|---|---|---|
ROUTER | ISaucerSwapV2Router public immutable ROUTER | The SaucerSwap V2 SwapRouter every fill swaps through. |
WHBAR | address public immutable WHBAR | The WHBAR HTS token, used as the HBAR leg of swap routes. |
collection | address public collection | HTS NFT collection whose serial numbers are order ids. |
costs | Costs public costs | Gas figures and gas price the vault charges and schedules by; see Costs. |
marketCount | uint32 public marketCount | Number of listed markets. Market ids run from 1 to marketCount. |
sweeps | mapping(uint256 marketId => SweepState) public sweeps | Each market's sweep chain; see SweepState. |
orderTypes | mapping(uint8 id => address impl) public orderTypes | The order-type strategy registry. orderTypes[id] is a view-only IOrderType; orderTypeActive gates whether NEW orders may use it. Append-only ids, so an order's bound type never changes. |
orderTypeActive | mapping(uint8 id => bool active) public orderTypeActive | Whether new orders may use order type id. |
orderTypeCount | uint8 public orderTypeCount | Number of registered order types. Ids run from 0 to orderTypeCount - 1. |
escrowed | mapping(address token => uint256) public escrowed | Tokens held on behalf of open orders, keyed by token (address(0) is HBAR). |
totalBudgets | uint256 public totalBudgets | HBAR prepaid for scheduled checks and fills of open orders. |
credits | mapping(address account => mapping(address token => uint256)) public credits | Payouts that could not be delivered and wait for claim. |
totalCredits | mapping(address token => uint256) public totalCredits | Sum of all accounts' credits in a token. |
Functions
constructor
constructor(address owner_, ISaucerSwapV2Router router_, address whbar_, Costs memory costs_)Deploy the vault. initialize must create the order NFT collection before orders can be placed.
- Mutability:
nonpayable
| Parameter | Type | Description |
|---|---|---|
owner_ | address | Initial owner (Ownable2Step). Non-zero. |
router_ | ISaucerSwapV2Router | SaucerSwap V2 SwapRouter. |
whbar_ | address | WHBAR HTS token, used as the HBAR leg of routes. |
costs_ | Costs memory | Initial costs; same bounds as setCosts. |
Reverts:
OwnableInvalidOwnerifowner_is zero.InvalidCostsifcosts_fails thesetCostschecks.
initialize
function initialize(string calldata name, string calldata symbol) external payable onlyOwnerCreate the order NFT collection. The vault is treasury and holds the supply and wipe keys.
- Access: Owner only (
onlyOwner) - Mutability:
payable - Selector:
0x4cd88b76(initialize(string,string))
Send the HTS creation fee as value (about 15 HBAR on testnet); any excess stays as surplus.
| Parameter | Type | Description |
|---|---|---|
name | string calldata | Collection name. |
symbol | string calldata | Collection symbol. |
Reverts:
OwnableUnauthorizedAccountif the caller is not the owner.AlreadyInitializedif the collection already exists.HtsError(CreateCollection) if HTS refuses to create it.
listMarket
function listMarket(Market calldata market) external onlyOwner returns (uint256 marketId)List a market and associate the vault with its HTS tokens. Validation and the storage write live in MarketRegistry; the bounds keep a market's guard from being switched off.
- Access: Owner only (
onlyOwner) - Mutability:
nonpayable - Selector:
0xd92c3f30(listMarket((address,address,uint8,uint8,bool,bool,address,address,uint8,uint8,address,uint24,bool,bool,(uint32,uint16,uint32,uint16),(uint32,uint32,uint16,uint16,uint8))))
| Parameter | Type | Description |
|---|---|---|
market | Market calldata | The market; Market, GuardParams and SweepParams give each field's bounds. |
| Returns | Type | Description |
|---|---|---|
marketId | uint256 | The new market's id; ids start at 1. |
Reverts:
OwnableUnauthorizedAccountif the caller is not the owner.InvalidMarketfor a zero pool, token or feed address, the same token twice, or two HBAR legs.InvalidGuardorInvalidSweepwhen the guard or sweep settings are out of bounds.HtsError(Associate) if the vault cannot associate with a market token.
updateMarket
function updateMarket(uint256 marketId, GuardParams calldata guard, SweepParams calldata sweepParams, bool active) external onlyOwnerTune a market's guard and sweep. Bounds keep the guard from being switched off.
- Access: Owner only (
onlyOwner) - Mutability:
nonpayable - Selector:
0x9a369eb6(updateMarket(uint256,(uint32,uint16,uint32,uint16),(uint32,uint32,uint16,uint16,uint8),bool))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
guard | GuardParams calldata | New guard settings (bounds in GuardParams); the slippage floor uses the stored poolFee. |
sweepParams | SweepParams calldata | New sweep settings (bounds in SweepParams). |
active | bool | Whether new orders may be placed. Open orders keep being checked either way. |
Reverts:
OwnableUnauthorizedAccountif the caller is not the owner.UnknownMarketif the market is not listed.InvalidGuardorInvalidSweepwhen the settings are out of bounds.
setCosts
function setCosts(Costs calldata costs_) external onlyOwnerReplace the gas figures and gas price the vault charges and schedules by.
- Access: Owner only (
onlyOwner) - Mutability:
nonpayable - Selector:
0x81c8ec30(setCosts((uint32,uint32,uint32,uint32,uint32,uint32,uint32,uint32,uint16)))
| Parameter | Type | Description |
|---|---|---|
costs_ | Costs calldata | New costs: scheduleGas, checkGas, fillGasHbarIn, fillGasTokenIn and gasPriceTinycents non-zero, and safetyBps at most 10,000. |
Reverts:
OwnableUnauthorizedAccountif the caller is not the owner.InvalidCostsif any of those checks fails.
registerOrderType
function registerOrderType(address impl) external onlyOwner returns (uint8 id)Register a view-only order-type strategy and return its id. Append-only: ids are never reused, so an order's bound type can never change under it. The new type is active for new orders at once.
- Access: Owner only (
onlyOwner) - Mutability:
nonpayable - Selector:
0xad03c047(registerOrderType(address))
| Parameter | Type | Description |
|---|---|---|
impl | address | The IOrderType implementation. Non-zero. |
| Returns | Type | Description |
|---|---|---|
id | uint8 | The new type's id: the previous orderTypeCount. The uint8 counter allows 255 types (ids 0 to 254). |
Reverts:
OwnableUnauthorizedAccountif the caller is not the owner.InvalidOrderParamsifimplis the zero address.
setOrderTypeActive
function setOrderTypeActive(uint8 id, bool active) external onlyOwnerPause or resume an order type for NEW orders. Existing orders of that type keep running and can always be cancelled; only placement is gated.
- Access: Owner only (
onlyOwner) - Mutability:
nonpayable - Selector:
0x1ef0f0c1(setOrderTypeActive(uint8,bool))
| Parameter | Type | Description |
|---|---|---|
id | uint8 | A registered order-type id. |
active | bool | Whether new orders may use it. |
Reverts:
OwnableUnauthorizedAccountif the caller is not the owner.UnknownOrderTypeifidis not registered.
fund
function fund() external payableEndow the vault with liquid HBAR to back the payer float, so its scheduled sweeps can always pay their gas at execution. Anyone may fund it; only the owner may withdraw the surplus above the float. Kept separate from receive, which only accepts swap proceeds from the router.
- Access: Anyone
- Mutability:
payable - Selector:
0xb60d4288(fund())
withdrawSurplus
function withdrawSurplus(address payable to) external onlyOwner nonReentrantWithdraw HBAR the vault holds beyond escrow, budgets, credits and the payer float.
- Access: Owner only (
onlyOwner) - Mutability:
nonpayable - Selector:
0x65e73e32(withdrawSurplus(address))
| Parameter | Type | Description |
|---|---|---|
to | address payable | Recipient of the surplus (OrderVaultLens.surplus previews the amount). |
Reverts:
OwnableUnauthorizedAccountif the caller is not the owner.InvalidAmountwhen there is no surplus.TransferFailediftodoes not accept the HBAR.
placeOrder
function placeOrder(PlaceParams calldata p) external payable nonReentrant returns (uint256 orderId)Escrow amountIn, mint the order NFT to the caller and make sure the market sweep is running.
- Access: Anyone
- Mutability:
payable - Selector:
0x7640d2be(placeOrder((uint32,uint8,uint8,uint128,uint128,uint16,uint40)))
msg.value is the check budget, plus amountIn when the input is HBAR. The caller needs auto-association slots or an association with collection. A token input needs an allowance of amountIn to the vault.
| Parameter | Type | Description |
|---|---|---|
p | PlaceParams calldata | The order; PlaceParams gives each field's bounds. |
| Returns | Type | Description |
|---|---|---|
orderId | uint256 | The new order's id, which is its NFT serial number. |
Reverts:
NotInitializedbeforeinitialize.UnknownMarketorMarketInactiveif the market is not listed or is paused.InvalidAmountifamountInis 0.UnknownOrderTypeorOrderTypeInactiveif the type is not registered or is disabled.InvalidOrderParamsif the type'svalidaterejects the parameters.InvalidSlippageunlessslippageBpsis abovepoolFee / 100and at mostguard.maxSlippageBps.InvalidExpiryunless the expiry is after the current block and at most 90 days ahead.WrongValueif msg.value is belowamountInfor an HBAR input.InsufficientBudgetif the budget is belowOrderVaultLens.minBudget.TransferFailedif pulling the input token fails.HtsError(MintorTransferNft) if minting the order NFT or sending it to the caller fails.
cancel
function cancel(uint256 orderId) external nonReentrantCancel an open order; escrow and unused budget go back to the NFT holder.
- Access: The order NFT's holder.
- Mutability:
nonpayable - Selector:
0x40e58ee5(cancel(uint256))
| Parameter | Type | Description |
|---|---|---|
orderId | uint256 | An open order whose NFT the caller holds. |
Reverts:
OrderNotOpenif the order is not open.NotHolderif the caller does not hold the order's NFT.
topUp
function topUp(uint256 orderId) external payable nonReentrantAdd HBAR to an order's check budget. Anyone may top up any order.
- Access: Anyone
- Mutability:
payable - Selector:
0x50017f3e(topUp(uint256))
msg.value is added to the budget. A parked order counts as funded again once its budget covers its reserve plus one solo check; for a funded order, the market's sweep is started or brought forward if needed.
| Parameter | Type | Description |
|---|---|---|
orderId | uint256 | An open order. |
Reverts:
InvalidAmountif msg.value is 0.OrderNotOpenif the order is not open.
executeOrder
function executeOrder(uint256 orderId) external nonReentrant returns (bool settled)Check one order now and fill or expire it if due. The caller pays gas; the budget is untouched.
- Access: Anyone
- Mutability:
nonpayable - Selector:
0x94f61134(executeOrder(uint256))
A failed swap does not revert: it emits FillFailed and returns false.
| Parameter | Type | Description |
|---|---|---|
orderId | uint256 | An open order. |
| Returns | Type | Description |
|---|---|---|
settled | bool | True if the order expired (and was refunded) or filled; false if its trigger is not met, the guard is not open, the oracle price is unusable, its strategy failed or the swap failed. |
Reverts:
OrderNotOpenif the order is not open.
claim
function claim(address token) external nonReentrantPull a payout that could not be delivered at settlement.
- Access: Anyone, for their own credits.
- Mutability:
nonpayable - Selector:
0x1e83409a(claim(address))
| Parameter | Type | Description |
|---|---|---|
token | address | The token to claim; address(0) for HBAR. |
Reverts:
NothingToClaimif the caller has no credit intoken.TransferFailedif the payout fails again.
sweep
function sweep(uint256 marketId, uint32 epoch) external nonReentrantCheck up to maxOrders open orders of a market, fill the ones whose trigger is met, and, when called by the Hedera Schedule Service, schedule the next sweep.
- Access: Anyone. The Hedera Schedule Service calls it as the vault itself (a scheduled sweep).
- Mutability:
nonpayable - Selector:
0x4ebfac46(sweep(uint256,uint32))
Scheduled calls arrive with msg.sender == this vault and carry the epoch they were scheduled under; a stale epoch means an earlier sweep replaced this one, so it returns at once. Scheduled calls debit each checked order's budget because the vault pays their fees. Manual calls are paid by the caller, debit nothing and ignore epoch. A manual call schedules the next sweep only when the chain is dead (see restartSweep).
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
epoch | uint32 | The epoch a scheduled call was created under; manual calls may pass any value. |
Reverts:
UnknownMarketif the market is not listed.
restartSweep
function restartSweep(uint256 marketId) external nonReentrantRestart a market's sweep chain if it stopped, e.g. because the vault could not pay a schedule. Anyone may call it; the caller pays for scheduling the next sweep.
- Access: Anyone
- Mutability:
nonpayable - Selector:
0xa17ba820(restartSweep(uint256))
The chain is dead when no schedule is pending, or the pending one is more than 120 seconds overdue (SweepMath.SWEEP_GRACE). The new sweep is scheduled minInterval seconds out.
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market with funded orders. |
Reverts:
UnknownMarketif the market is not listed.NoFundedOrdersif no funded order is waiting.SweepAliveif a sweep is still pending.
fillFromVault
function fillFromVault(uint256 orderId, uint256 oraclePrice, uint256 poolPrice) external returns (uint256 amountOut)Settle a fill. Only callable by the vault itself, so a failed swap can be caught.
- Access: The vault itself only.
- Mutability:
nonpayable - Selector:
0x46625860(fillFromVault(uint256,uint256,uint256))
The swap's floor is the Chainlink value of amountIn less the order's slippage, or the order type's minOut when that is higher.
| Parameter | Type | Description |
|---|---|---|
orderId | uint256 | The order to fill. |
oraclePrice | uint256 | Chainlink cross price the floor is computed from (quote per 1 base, 8 decimals). |
poolPrice | uint256 | Pool TWAP price, reported in OrderFilled. |
| Returns | Type | Description |
|---|---|---|
amountOut | uint256 | Output paid to the holder (or credited for claim), in the output token's raw units. |
Reverts:
OnlySelffor any other caller. A swap below the floor reverts in the router.
getMarket
function getMarket(uint256 marketId) external view returns (Market memory)A listed market's configuration.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0xeb44fdd3(getMarket(uint256))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market (1 to marketCount). |
| Returns | Type | Description |
|---|---|---|
| – | Market memory | The market. |
Reverts:
UnknownMarketif the market is not listed.
getOrder
function getOrder(uint256 orderId) external view returns (Order memory)An order as stored. Settled orders keep their record; an unknown id returns all zeros (Status.None).
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0xd09ef241(getOrder(uint256))
| Parameter | Type | Description |
|---|---|---|
orderId | uint256 | The order id (its NFT serial number). |
| Returns | Type | Description |
|---|---|---|
| – | Order memory | The order. |
openOrders
function openOrders(uint256 marketId) external view returns (uint256[] memory)Ids of a market's open orders, in the list order sweeps rotate through from sweeps(marketId).cursor.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x447c1e8c(openOrders(uint256))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | The market; an unlisted one returns an empty list. |
| Returns | Type | Description |
|---|---|---|
| – | uint256[] memory | The open order ids. |
holderOf
function holderOf(uint256 orderId) public view returns (address)Current holder of an order's NFT: the account that can cancel it and receives its proceeds.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0xdbacc237(holderOf(uint256))
| Parameter | Type | Description |
|---|---|---|
orderId | uint256 | The order id. |
| Returns | Type | Description |
|---|---|---|
| – | address | The holder, from the collection's ERC-721 ownerOf. |
guardReading
function guardReading(uint256 marketId) public view returns (GuardReading memory)Chainlink price, pool TWAP price and the guard verdict for a market.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x8e6caf83(guardReading(uint256))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
| Returns | Type | Description |
|---|---|---|
| – | GuardReading memory | The reading; see GuardReading. |
Reverts:
UnknownMarketif the market is not listed.
receive
receive() external payableReceives HBAR the router unwraps when an order buys HBAR.
- Access: The SaucerSwap router only.
- Mutability:
payable
Reverts:
NotRouterfor any other sender; endow the vault throughfund.
Events
CollectionCreated
event CollectionCreated(address collection)initialize created the order NFT collection.
- Topic 0:
0x75432e2e509efcaf947efcc7a5a6b6b3562425b29e9725c7a4a5c652291ac35d
| Field | Type | Indexed | Description |
|---|---|---|---|
collection | address | no | The collection's token address. |
MarketListed
event MarketListed(uint256 indexed marketId, address base, address quote, address pool, uint24 poolFee)The owner listed a market.
- Topic 0:
0x862dcbceb6a07995dc548083959f333b526718ea1a87a0ca0fb44408b9208e66
| Field | Type | Indexed | Description |
|---|---|---|---|
marketId | uint256 | yes | The new market's id. |
base | address | no | Base token address. |
quote | address | no | Quote token address. |
pool | address | no | The SaucerSwap V2 pool it trades on. |
poolFee | uint24 | no | The pool's fee, in hundredths of a basis point. |
MarketUpdated
event MarketUpdated(uint256 indexed marketId)The owner changed a market's guard, sweep or active flag.
- Topic 0:
0x81037e11e81e97d68af7eab8fcc753234b4a41564fe724d62db9db716f054785
| Field | Type | Indexed | Description |
|---|---|---|---|
marketId | uint256 | yes | The market. |
CostsUpdated
event CostsUpdated(Costs costs)The costs were set, at deployment or by setCosts.
- Topic 0:
0x5d1a796c088d803ba26be6a6756403de03c84173b28b892e34d7a46d9b2b7f88
| Field | Type | Indexed | Description |
|---|---|---|---|
costs | Costs | no | The new costs. |
OrderPlaced
event OrderPlaced(uint256 indexed orderId, uint256 indexed marketId, address indexed maker, Side side, uint8 orderType, uint256 amountIn, uint256 typeParam, uint256 slippageBps, uint256 expiry, uint256 budget)An order was placed and its NFT minted to the maker.
- Topic 0:
0x94a9ab2daa7366c4b87412378f3606519f7ab5f3a446a76c08d7e4a58a48f4ce
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order id (its NFT serial number). |
marketId | uint256 | yes | The market. |
maker | address | yes | The caller, who received the order NFT. |
side | Side | no | Sell the base, or buy it. |
orderType | uint8 | no | The order-type id. |
amountIn | uint256 | no | Escrowed input, in the input token's raw units. |
typeParam | uint256 | no | The type's parameter (trigger price or trail). |
slippageBps | uint256 | no | Slippage tolerance, in bps. |
expiry | uint256 | no | Expiry time (unix seconds). |
budget | uint256 | no | Check budget in tinybar: msg.value, less amountIn for an HBAR input. |
OrderTypeRegistered
event OrderTypeRegistered(uint8 indexed id, address impl)The owner registered an order type.
- Topic 0:
0x0ea9184fb000cd0c7d236aee300da88e7824977af916b5373ef14ecca987c8e7
| Field | Type | Indexed | Description |
|---|---|---|---|
id | uint8 | yes | The type's id. |
impl | address | no | The IOrderType implementation. |
OrderTypeActiveSet
event OrderTypeActiveSet(uint8 indexed id, bool active)An order type was enabled or disabled for new orders (registration also emits it, as enabled).
- Topic 0:
0x5cd60a524ada1d3093085ffd5ceb88f0e292ca05df7ab065c1488cb32188210d
| Field | Type | Indexed | Description |
|---|---|---|---|
id | uint8 | yes | The type's id. |
active | bool | no | Whether new orders may use it. |
OrderStateUpdated
event OrderStateUpdated(uint256 indexed orderId, bytes32 state)A strategy returned new per-order state (e.g. a trailing stop raised its peak); the vault stored it.
- Topic 0:
0x5dd40b698b74bd8012621fe84b0c6d41dd12d7b7e4b8b05c45911abd5794fa6c
Emitted by sweeps; executeOrder stores a new state without this event.
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
state | bytes32 | no | The stored state. |
OrderEvalSkipped
event OrderEvalSkipped(uint256 indexed orderId)A strategy reverted or ran out of its gas stipend during a sweep; the order was skipped, not filled.
- Topic 0:
0x57c4f0edc9cbbe9de37ac672be47f6f6d952ea877b93512c97c2b1eec5ce1d38
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The skipped order. |
OrderFilled
event OrderFilled(uint256 indexed orderId, address indexed holder, uint256 amountIn, uint256 amountOut, uint256 minAmountOut, uint256 oraclePrice, uint256 poolPrice, uint256 budgetRefund)An order filled.
- Topic 0:
0x4eac0bcdf713c4feb523019bdbf1c5035d9fcc44aadb6a69e0777e235082f6eb
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
holder | address | yes | The NFT holder, who received the output. |
amountIn | uint256 | no | Input swapped, in the input token's raw units. |
amountOut | uint256 | no | Output received, in the output token's raw units. |
minAmountOut | uint256 | no | The floor the swap had to meet. |
oraclePrice | uint256 | no | Chainlink cross price at the fill (quote per 1 base, 8 decimals). |
poolPrice | uint256 | no | Pool TWAP price at the fill, same units. |
budgetRefund | uint256 | no | Unspent budget returned to the holder, in tinybar. |
OrderCancelled
event OrderCancelled(uint256 indexed orderId, address indexed holder, uint256 refund, uint256 budgetRefund)The holder cancelled an order.
- Topic 0:
0x8cd7e382eb42bcc84841dacd15adda3bdd77aefce75edd49238bd47995b1f968
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
holder | address | yes | The NFT holder, who received the refunds. |
refund | uint256 | no | Escrow returned, in the input token's raw units. |
budgetRefund | uint256 | no | Unspent budget returned, in tinybar. |
OrderExpired
event OrderExpired(uint256 indexed orderId, address indexed holder, uint256 refund, uint256 budgetRefund)An order reached its expiry unfilled and was refunded.
- Topic 0:
0x071305708de69f801b70c8f5dd48f7fbd493931f97e27d35b0bc83034464b074
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
holder | address | yes | The NFT holder, who received the refunds. |
refund | uint256 | no | Escrow returned, in the input token's raw units. |
budgetRefund | uint256 | no | Unspent budget returned, in tinybar. |
OrderChecked
event OrderChecked(uint256 indexed orderId, uint256 charged, uint256 budgetLeft)A scheduled sweep charged an order for its check.
- Topic 0:
0x1a7dbf431965c6067a9b8aea714120177a1e0d555a6dd0078b62e17d9ae1847b
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
charged | uint256 | no | Tinybar taken from its budget. |
budgetLeft | uint256 | no | Budget remaining, in tinybar. |
FillHeld
event FillHeld(uint256 indexed orderId, GuardState reason, uint256 oraclePrice, uint256 poolPrice)An order's trigger was met but the guard was not open, so it was not filled.
- Topic 0:
0x4da863769c919db72a1edd2c42732b7959df850e7fe9379da40679059d8f5ad9
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
reason | GuardState | no | The guard's verdict. |
oraclePrice | uint256 | no | Chainlink cross price (quote per 1 base, 8 decimals). |
poolPrice | uint256 | no | Pool TWAP price, same units. |
FillFailed
event FillFailed(uint256 indexed orderId, bytes reason)A fill's swap reverted (for example, output below the floor); the order stays open.
- Topic 0:
0x8dc9bf5450814d2f276260acfcf62306865189dfc3855d241d2a565159cfc5ea
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
reason | bytes | no | The revert data. |
BudgetExhausted
event BudgetExhausted(uint256 indexed orderId, uint256 budgetLeft)An order's budget can no longer pay for a check, so it was parked until a topUp.
- Topic 0:
0xe3bbed9ba4ea66661cbf21701baf30a52ea330ce76f1be3ca59360048ecb1894
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
budgetLeft | uint256 | no | Budget remaining after the park fee, in tinybar. |
BudgetToppedUp
event BudgetToppedUp(uint256 indexed orderId, address indexed from, uint256 amount, uint256 budget)HBAR was added to an order's budget.
- Topic 0:
0x908e184df46f5e7e1ef7f34f02b3f94a910f9d1e67c2fbdf158b549758370acb
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
from | address | yes | Who paid. |
amount | uint256 | no | Tinybar added. |
budget | uint256 | no | The new budget, in tinybar. |
SweepScheduled
event SweepScheduled(uint256 indexed marketId, address schedule, uint256 executeAt, uint256 epoch)The vault scheduled a market's next sweep with the Hedera Schedule Service.
- Topic 0:
0x3bafc8a0342d1904e9fc16d0a85040ad804014f5ca02e351a4c038052a50dc99
| Field | Type | Indexed | Description |
|---|---|---|---|
marketId | uint256 | yes | The market. |
schedule | address | no | The schedule's address. |
executeAt | uint256 | no | When it is due (unix seconds). |
epoch | uint256 | no | The epoch it carries. |
SweepSuperseded
event SweepSuperseded(uint256 indexed marketId, uint256 epoch)A scheduled sweep carried an outdated epoch and returned without work.
- Topic 0:
0x36655c53ca0cedf0e1dacadc4828ea2f0830d23305bf707d35f39874077a3895
| Field | Type | Indexed | Description |
|---|---|---|---|
marketId | uint256 | yes | The market. |
epoch | uint256 | no | The outdated epoch it carried. |
SweepBroughtForward
event SweepBroughtForward(uint256 indexed orderId, uint256 charged, uint256 budgetLeft)An order needed a check sooner than the pending sweep and paid for the superseded run.
- Topic 0:
0xb39ae012f5454cab6d0274a37ff2818cc20c0a49ef3a632cd3ab4d6ff69a5d02
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
charged | uint256 | no | Tinybar taken from its budget. |
budgetLeft | uint256 | no | Budget remaining, in tinybar. |
SweepScheduleFailed
event SweepScheduleFailed(uint256 indexed marketId, int64 responseCode)The Hedera Schedule Service refused a sweep schedule; any pending sweep stays valid.
- Topic 0:
0x377af519127f551fc264ad444e60aa112009b23be8fbbd9c4e9e44b571521170
| Field | Type | Indexed | Description |
|---|---|---|---|
marketId | uint256 | yes | The market. |
responseCode | int64 | no | The response code returned. |
SweepExecuted
event SweepExecuted(uint256 indexed marketId, bool scheduled, GuardState guard, uint256 checked, uint256 filled, uint256 openOrders)A sweep ran.
- Topic 0:
0xf65ab711cd721b9466fddd4002742c7953ea578b6265ea5d726c7260bd1688f5
| Field | Type | Indexed | Description |
|---|---|---|---|
marketId | uint256 | yes | The market. |
scheduled | bool | no | True for a scheduled sweep, false for a manual call. |
guard | GuardState | no | The guard's verdict during the sweep. |
checked | uint256 | no | Orders checked. |
filled | uint256 | no | Orders filled. |
openOrders | uint256 | no | Open orders left in the market. |
Credited
event Credited(address indexed account, address indexed token, uint256 amount)A payout could not be delivered and was credited for claim.
- Topic 0:
0x4e45da441832cf53bdaa69235704fc0575e68210f459ee1562911024b12967d5
| Field | Type | Indexed | Description |
|---|---|---|---|
account | address | yes | The recipient. |
token | address | yes | The token; address(0) for HBAR. |
amount | uint256 | no | Amount credited, in the token's raw units. |
Claimed
event Claimed(address indexed account, address indexed token, uint256 amount)An account claimed its credit.
- Topic 0:
0xf7a40077ff7a04c7e61f6f26fb13774259ddf1b6bce9ecf26a8276cdd3992683
| Field | Type | Indexed | Description |
|---|---|---|---|
account | address | yes | The claimer. |
token | address | yes | The token; address(0) for HBAR. |
amount | uint256 | no | Amount paid out, in the token's raw units. |
NftSettlementFailed
event NftSettlementFailed(uint256 indexed orderId, int64 responseCode)Retiring a settled order's NFT failed; the settlement itself went through.
- Topic 0:
0x1bdc79a178a73212b2174089771536dfb84d194c995fe99585060c1d1c6043cd
| Field | Type | Indexed | Description |
|---|---|---|---|
orderId | uint256 | yes | The order. |
responseCode | int64 | no | The HTS response code. |
SurplusWithdrawn
event SurplusWithdrawn(address indexed to, uint256 amount)The owner withdrew surplus HBAR.
- Topic 0:
0xb94528ab6dc2c15743a47b933115b331b7beae78712677f1e345a9f1ae84bbd1
| Field | Type | Indexed | Description |
|---|---|---|---|
to | address | yes | The recipient. |
amount | uint256 | no | Tinybar sent. |
Funded
event Funded(address indexed from, uint256 amount)Someone endowed the vault through fund.
- Topic 0:
0x5af8184bef8e4b45eb9f6ed7734d04da38ced226495548f46e0c8ff8d7d9a524
| Field | Type | Indexed | Description |
|---|---|---|---|
from | address | yes | Who paid. |
amount | uint256 | no | Tinybar received. |
Errors
AlreadyInitialized
error AlreadyInitialized()initialize was called after the collection already exists.
- Selector:
0x0dc149f0
NotInitialized
error NotInitialized()An order was placed before initialize created the collection.
- Selector:
0x87138d5c
UnknownMarket
error UnknownMarket(uint256 marketId)No market is listed under this id.
- Selector:
0x69616b87
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | The id asked for. |
MarketInactive
error MarketInactive(uint256 marketId)The market is paused for new orders.
- Selector:
0x427a54ec
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | The market. |
InvalidMarket
error InvalidMarket()listMarket got a zero pool, token or feed address, the same token twice, or two HBAR legs.
- Selector:
0x9db8d5b1
Raised by MarketRegistry when listing or tuning a market; declared here so the vault's ABI decodes them.
InvalidGuard
error InvalidGuard()Guard settings outside the GuardParams bounds (raised by MarketRegistry).
- Selector:
0x15e33ca3
InvalidSweep
error InvalidSweep()Sweep settings outside the SweepParams bounds (raised by MarketRegistry).
- Selector:
0x3b77a1fd
InvalidCosts
error InvalidCosts()Costs failing the setCosts checks, or the 0x168 exchange-rate system contract did not answer.
- Selector:
0x1b44ea81
InvalidAmount
error InvalidAmount()A zero amountIn, a topUp with no value, or a withdrawSurplus with no surplus.
- Selector:
0x2c5211c6
InvalidTrigger
error InvalidTrigger()Not raised by this vault; declared so its ABI still decodes the earlier fixed-trigger vault's error for a zero trigger price.
- Selector:
0xa768d7fd
UnknownOrderType
error UnknownOrderType(uint8 id)No order type is registered under this id.
- Selector:
0xb90a1f38
| Parameter | Type | Description |
|---|---|---|
id | uint8 | The id asked for. |
OrderTypeInactive
error OrderTypeInactive(uint8 id)The order type is disabled for new orders.
- Selector:
0x33970f22
| Parameter | Type | Description |
|---|---|---|
id | uint8 | The type's id. |
InvalidOrderParams
error InvalidOrderParams()The order type's validate rejected the parameters, or registerOrderType got the zero address.
- Selector:
0xfbe18ad3
InvalidSlippage
error InvalidSlippage(uint256 slippageBps, uint256 minBps, uint256 maxBps)The order's slippage is outside the market's bounds.
- Selector:
0x93b7d837
| Parameter | Type | Description |
|---|---|---|
slippageBps | uint256 | The slippage given, in bps. |
minBps | uint256 | The smallest accepted: the pool fee in bps (poolFee / 100) plus 1. |
maxBps | uint256 | The largest accepted: the market's guard.maxSlippageBps. |
InvalidExpiry
error InvalidExpiry(uint256 expiry)The expiry is not after the current block, or more than 90 days ahead.
- Selector:
0x3accc52b
| Parameter | Type | Description |
|---|---|---|
expiry | uint256 | The expiry given. |
InsufficientBudget
error InsufficientBudget(uint256 provided, uint256 required)The check budget is below the minimum (OrderVaultLens.minBudget).
- Selector:
0xa9a711d0
| Parameter | Type | Description |
|---|---|---|
provided | uint256 | The budget sent, in tinybar. |
required | uint256 | The minimum, in tinybar. |
WrongValue
error WrongValue(uint256 sent, uint256 expected)An HBAR-input order sent less value than its amountIn.
- Selector:
0x195a3ca1
| Parameter | Type | Description |
|---|---|---|
sent | uint256 | msg.value, in tinybar. |
expected | uint256 | The order's amountIn. |
OrderNotOpen
error OrderNotOpen(uint256 orderId)The order is not open (unknown, filled, cancelled or expired).
- Selector:
0x410e0437
| Parameter | Type | Description |
|---|---|---|
orderId | uint256 | The order. |
NotHolder
error NotHolder(uint256 orderId, address caller)The caller does not hold the order's NFT.
- Selector:
0x2f5ea621
| Parameter | Type | Description |
|---|---|---|
orderId | uint256 | The order. |
caller | address | The caller. |
OnlySelf
error OnlySelf()fillFromVault was called by someone other than the vault.
- Selector:
0x14d4a4e8
NothingToClaim
error NothingToClaim()The caller has no credit in this token.
- Selector:
0x969bf728
TransferFailed
error TransferFailed()An HBAR send or a token transfer failed.
- Selector:
0x90b8ec18
SweepAlive
error SweepAlive(uint256 marketId, uint256 nextSweepAt)restartSweep was called while a sweep is still pending.
- Selector:
0x3219cffb
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | The market. |
nextSweepAt | uint256 | When the pending sweep is due (unix seconds). |
NoFundedOrders
error NoFundedOrders(uint256 marketId)restartSweep was called for a market with no funded orders.
- Selector:
0x30a2f79b
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | The market. |
NotRouter
error NotRouter(address sender)HBAR arrived through receive from someone other than the router; use fund instead.
- Selector:
0x2462ed09
| Parameter | Type | Description |
|---|---|---|
sender | address | The sender. |
Inherited and imported
Part of this ABI but declared in Ownable2Step, Ownable, ReentrancyGuard, SafeCast; the text is the upstream NatSpec.
acceptOwnership
function acceptOwnership() public- Inherited from
Ownable2Step - Mutability:
nonpayable - Selector:
0x79ba5097(acceptOwnership())
The new owner accepts the ownership transfer.
owner
function owner() public view returns (address)- Inherited from
Ownable - Access: Anyone (read-only)
- Mutability:
view - Selector:
0x8da5cb5b(owner())
Returns the address of the current owner.
| Returns | Type | Description |
|---|---|---|
| – | address | – |
pendingOwner
function pendingOwner() public view returns (address)- Inherited from
Ownable2Step - Access: Anyone (read-only)
- Mutability:
view - Selector:
0xe30c3978(pendingOwner())
Returns the address of the pending owner.
| Returns | Type | Description |
|---|---|---|
| – | address | – |
renounceOwnership
function renounceOwnership() public onlyOwner- Inherited from
Ownable - Access: Owner only (
onlyOwner) - Mutability:
nonpayable - Selector:
0x715018a6(renounceOwnership())
Leaves the contract without owner. It will not be possible to call onlyOwner functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner.
Reverts:
OwnableUnauthorizedAccountif the caller is not the owner.
transferOwnership
function transferOwnership(address newOwner) public onlyOwner- Inherited from
Ownable2Step - Access: Owner only (
onlyOwner) - Mutability:
nonpayable - Selector:
0xf2fde38b(transferOwnership(address))
Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. Can only be called by the current owner. Setting newOwner to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
| Parameter | Type | Description |
|---|---|---|
newOwner | address | – |
Reverts:
OwnableUnauthorizedAccountif the caller is not the owner.
OwnershipTransferStarted
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner)- Inherited from
Ownable2Step - Topic 0:
0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700
| Field | Type | Indexed | Description |
|---|---|---|---|
previousOwner | address | yes | – |
newOwner | address | yes | – |
OwnershipTransferred
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)- Inherited from
Ownable - Topic 0:
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0
| Field | Type | Indexed | Description |
|---|---|---|---|
previousOwner | address | yes | – |
newOwner | address | yes | – |
OwnableInvalidOwner
error OwnableInvalidOwner(address owner)- Declared in
Ownable - Selector:
0x1e4fbdf7
The owner is not a valid owner account. (eg. address(0))
| Parameter | Type | Description |
|---|---|---|
owner | address | – |
OwnableUnauthorizedAccount
error OwnableUnauthorizedAccount(address account)- Declared in
Ownable - Selector:
0x118cdaa7
The caller account is not authorized to perform an operation.
| Parameter | Type | Description |
|---|---|---|
account | address | – |
ReentrancyGuardReentrantCall
error ReentrancyGuardReentrantCall()- Declared in
ReentrancyGuard - Selector:
0x3ee5aeb5
Unauthorized reentrant call.
SafeCastOverflowedUintDowncast
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value)- Declared in
SafeCast - Selector:
0x6dfcc650
Value doesn't fit in a uint of bits size.
| Parameter | Type | Description |
|---|---|---|
bits | uint8 | – |
value | uint256 | – |
Other errors in this ABI: HtsError.
OrderVaultLens
- Source:
packages/foundry/contracts/OrderVaultLens.sol - Hedera testnet:
0x71bef6696d1c684f2f9d1581f4adb07e9d7e9d8e
Read-only previews of what an OrderVault will charge and when it will check, for the frontend and the Debug page. It holds no state and no funds; every figure is computed from the vault's raw state with SweepMath, the same code the vault charges and schedules by, so a preview and the vault's own number cannot drift apart. Kept out of the vault so the vault stays well under the 24 KB limit.
Public variables
| Name | Declaration | Description |
|---|---|---|
VAULT | OrderVault public immutable VAULT | The vault this lens reads. |
Functions
constructor
constructor(OrderVault vault_)- Mutability:
nonpayable
| Parameter | Type | Description |
|---|---|---|
vault_ | OrderVault | The OrderVault to read. |
checkCost
function checkCost(uint256 marketId) external view returns (uint256)HBAR (tinybar) charged to an order per scheduled check if it were the only funded order.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x11b4a832(checkCost(uint256))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Tinybar per check. |
Reverts:
UnknownMarket(from the vault) if the market is not listed.
checkCostShared
function checkCostShared(uint256 fundedOrders) external view returns (uint256)HBAR (tinybar) charged per check when fundedOrders orders share the sweep.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x9917f638(checkCostShared(uint256))
| Parameter | Type | Description |
|---|---|---|
fundedOrders | uint256 | Orders sharing the sweep's fixed cost; 0 is treated as 1. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Tinybar per check. |
fillCost
function fillCost(uint256 marketId, Side side) external view returns (uint256)HBAR (tinybar) an order always keeps back: its fill, plus its part of a final sweep.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x6654a22e(fillCost(uint256,uint8))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
side | Side | The order's side, which decides whether its input is HBAR. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | The reserve, in tinybar. |
Reverts:
UnknownMarket(from the vault) if the market is not listed.
minBudget
function minBudget(uint256 marketId, Side side) external view returns (uint256)Smallest budget placeOrder accepts: the reserve plus MIN_CHECKS_FUNDED solo checks.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x53961d08(minBudget(uint256,uint8))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
side | Side | The order's side, which decides whether its input is HBAR. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | The minimum budget, in tinybar. |
Reverts:
UnknownMarket(from the vault) if the market is not listed.
sweepGasLimit
function sweepGasLimit(uint256 marketId) public view returns (uint256)Gas limit the vault gives a market's next scheduled sweep, at today's open orders.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x003ce056(sweepGasLimit(uint256))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | The gas limit. |
Reverts:
UnknownMarket(from the vault) if the market is not listed.
payerFloat
function payerFloat() public view returns (uint256 float)HBAR the vault keeps liquid so a scheduled sweep can always pay its gas: the costliest funded market's sweep at the configured price.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x150ce9e2(payerFloat())
| Returns | Type | Description |
|---|---|---|
float | uint256 | The float, in tinybar. |
surplus
function surplus() external view returns (uint256)HBAR withdrawSurplus would pay out now: the balance beyond escrow, budgets, credits and the float.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x13888565(surplus())
| Returns | Type | Description |
|---|---|---|
| – | uint256 | The surplus, in tinybar. |
previewCharges
function previewCharges(uint256 marketId) external view returns (uint256 share, uint256 parkFee)What a scheduled sweep of marketId would charge if it ran now: share per paying order, and parkFee for an order whose budget can no longer cover a check (it is parked instead).
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0xc7fbcd37(previewCharges(uint256))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
| Returns | Type | Description |
|---|---|---|
share | uint256 | Tinybar charged to each order that can pay. |
parkFee | uint256 | Tinybar charged to each order that is parked. |
Reverts:
UnknownMarket(from the vault) if the market is not listed.
nextBatch
function nextBatch(uint256 marketId) public view returns (uint256[] memory batch)The orders the next sweep of marketId will visit, in order: up to maxOrders, starting at the market's rotating cursor.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x91b6eb4f(nextBatch(uint256))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
| Returns | Type | Description |
|---|---|---|
batch | uint256[] memory | The order ids, in visiting order. |
Reverts:
UnknownMarket(from the vault) if the market is not listed.
nextCheckDelay
function nextCheckDelay(uint256 marketId, uint8 orderType, Side side, uint128 typeParam, uint256 expiry) external view returns (uint256)Seconds until an order of orderType with typeParam would next be checked, at today's price.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x887aebc5(nextCheckDelay(uint256,uint8,uint8,uint128,uint256))
The rule a sweep applies, for an order not placed yet (no per-type state); the frontend sizes budgets with it. Held or triggered orders, and an unknown or failing type, get minInterval.
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
orderType | uint8 | The order-type id. |
side | Side | The order's side. |
typeParam | uint128 | The type's parameter (trigger price or trail), as in PlaceParams. |
expiry | uint256 | The order's expiry (unix seconds); the delay never runs past it. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Seconds until the check, within the market's minInterval and maxInterval. |
Reverts:
UnknownMarket(from the vault) if the market is not listed.
orderNextCheckDelay
function orderNextCheckDelay(uint256 orderId) external view returns (uint256)Seconds until a placed order would next be checked at today's price, using its live per-type state (e.g. a trailing stop's peak). Not open, or a failing strategy: minInterval.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x47c60284(orderNextCheckDelay(uint256))
| Parameter | Type | Description |
|---|---|---|
orderId | uint256 | The order. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Seconds until the check. |
Reverts:
UnknownMarket(from the vault) for an unknown order id, whose market id reads as 0.
sweepStatus
function sweepStatus(uint256 marketId) external view returns (SweepStatus status, uint256 nextSweepAt)Whether a market's checks are running. Stalled means funded orders are waiting but no schedule will fire (the vault could not pay one, or it was missed); anyone may restartSweep.
- Access: Anyone (read-only)
- Mutability:
view - Selector:
0x28677fcf(sweepStatus(uint256))
| Parameter | Type | Description |
|---|---|---|
marketId | uint256 | A listed market. |
| Returns | Type | Description |
|---|---|---|
status | SweepStatus | Idle, Scheduled or Stalled. |
nextSweepAt | uint256 | When the pending (or missed) sweep is due (unix seconds); 0 when Idle. |
Reverts:
UnknownMarket(from the vault) if the market is not listed.
Errors
InvalidCosts
error InvalidCosts()The exchange-rate system contract did not answer; the same error the vault raises for it.
- Selector:
0x1b44ea81
LimitOrderType
- Source:
packages/foundry/contracts/ordertypes/LimitOrderType.sol - Implements
IOrderType - Hedera testnet:
0x0b6dedd3fdf794be447efc4da514207259977cca
Sell at or above a price, or buy at or below it. Stateless. Behaviour is identical to the original fixed Sell+AtOrAbove / Buy+AtOrBelow logic, so existing orders and proofs are unchanged.
script/Deploy.s.sol registers it as order type 0.
Functions
validate
function validate(Side, uint128 amountIn, uint128 param, uint16, uint40, uint40) external pure returns (bool)Accepts either side with a non-zero amount and trigger price.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0x0956722c(validate(uint8,uint128,uint128,uint16,uint40,uint40))
| Parameter | Type | Description |
|---|---|---|
| (unnamed) | Side | Unused by this type. |
amountIn | uint128 | Amount escrowed; greater than 0. |
param | uint128 | Trigger price, quote per 1 base with 8 decimals; greater than 0. |
| (unnamed) | uint16 | Unused by this type. |
| (unnamed) | uint40 | Unused by this type. |
| (unnamed) | uint40 | Unused by this type. |
| Returns | Type | Description |
|---|---|---|
| – | bool | Whether the parameters are valid. |
evaluate
function evaluate(Side side, uint128 param, bytes32 state, uint256 oraclePrice) external pure returns (uint256 distanceBps, bytes32 newState)Met when the price is at or above the trigger for a sell, at or below it for a buy.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0xf25ecc56(evaluate(uint8,uint128,bytes32,uint256))
| Parameter | Type | Description |
|---|---|---|
side | Side | Sell or buy. |
param | uint128 | Trigger price (quote per 1 base, 8 decimals). |
state | bytes32 | Returned unchanged: the type is stateless. |
oraclePrice | uint256 | The Chainlink cross price for the market. |
| Returns | Type | Description |
|---|---|---|
distanceBps | uint256 | 0 when the trigger is met; otherwise the gap in bps of the price, at least 1. |
newState | bytes32 | state, unchanged. |
minOut
function minOut(Side, uint128, uint128, uint256) external pure returns (uint256)No extra floor, so the vault's own Chainlink floor applies.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0x2966791c(minOut(uint8,uint128,uint128,uint256))
| Parameter | Type | Description |
|---|---|---|
| (unnamed) | Side | Unused by this type. |
| (unnamed) | uint128 | Unused by this type. |
| (unnamed) | uint128 | Unused by this type. |
| (unnamed) | uint256 | Unused by this type. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Always 0. |
StopOrderType
- Source:
packages/foundry/contracts/ordertypes/StopOrderType.sol - Implements
IOrderType - Hedera testnet:
0x11dfda5ca30d3ed806d24ec0cc8eee06b0872c2b
A stop-loss (sell at or below a price) or a stop-buy (buy at or above it). Stateless. Behaviour is identical to the original fixed Sell+AtOrBelow / Buy+AtOrAbove logic.
script/Deploy.s.sol registers it as order type 1.
Functions
validate
function validate(Side, uint128 amountIn, uint128 param, uint16, uint40, uint40) external pure returns (bool)Accepts either side with a non-zero amount and trigger price.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0x0956722c(validate(uint8,uint128,uint128,uint16,uint40,uint40))
| Parameter | Type | Description |
|---|---|---|
| (unnamed) | Side | Unused by this type. |
amountIn | uint128 | Amount escrowed; greater than 0. |
param | uint128 | Trigger price, quote per 1 base with 8 decimals; greater than 0. |
| (unnamed) | uint16 | Unused by this type. |
| (unnamed) | uint40 | Unused by this type. |
| (unnamed) | uint40 | Unused by this type. |
| Returns | Type | Description |
|---|---|---|
| – | bool | Whether the parameters are valid. |
evaluate
function evaluate(Side side, uint128 param, bytes32 state, uint256 oraclePrice) external pure returns (uint256 distanceBps, bytes32 newState)Met when the price is at or below the trigger for a sell, at or above it for a buy.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0xf25ecc56(evaluate(uint8,uint128,bytes32,uint256))
| Parameter | Type | Description |
|---|---|---|
side | Side | Sell or buy. |
param | uint128 | Trigger price (quote per 1 base, 8 decimals). |
state | bytes32 | Returned unchanged: the type is stateless. |
oraclePrice | uint256 | The Chainlink cross price for the market. |
| Returns | Type | Description |
|---|---|---|
distanceBps | uint256 | 0 when the trigger is met; otherwise the gap in bps of the price, at least 1. |
newState | bytes32 | state, unchanged. |
minOut
function minOut(Side, uint128, uint128, uint256) external pure returns (uint256)No extra floor, so the vault's own Chainlink floor applies.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0x2966791c(minOut(uint8,uint128,uint128,uint256))
| Parameter | Type | Description |
|---|---|---|
| (unnamed) | Side | Unused by this type. |
| (unnamed) | uint128 | Unused by this type. |
| (unnamed) | uint128 | Unused by this type. |
| (unnamed) | uint256 | Unused by this type. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Always 0. |
TrailingStopType
- Source:
packages/foundry/contracts/ordertypes/TrailingStopType.sol - Implements
IOrderType - Hedera testnet:
0x2e449f0ed73d54239b9cd647d0a23ab1d9c78a36
Rides the price up and fires on a pullback: it tracks the highest Chainlink price the order has seen at a check (the "peak"), and the trigger is peak × (1 − trail). As the peak rises the trigger rises with it; it never moves down.
The peak is the maximum of the oracle sampled at scheduled checks, not the true continuous high, so a spike that reverses entirely between two checks is not captured. This is inherent to a pay-per-check, on-chain design and is stated in the UI and docs. Per-order state is the peak, returned to the vault which stores it; this contract is pure and cannot itself write anything. script/Deploy.s.sol registers it as order type 2.
Public variables
| Name | Declaration | Description |
|---|---|---|
MIN_TRAIL_BPS | uint128 public constant MIN_TRAIL_BPS = 50 | Smallest trail accepted, in bps (0.5%). |
MAX_TRAIL_BPS | uint128 public constant MAX_TRAIL_BPS = 5000 | Largest trail accepted, in bps (50%). |
Functions
validate
function validate(Side side, uint128 amountIn, uint128 param, uint16, uint40, uint40) external pure returns (bool)Accepts a sell with a non-zero amount and a trail of 50 to 5,000 bps.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0x0956722c(validate(uint8,uint128,uint128,uint16,uint40,uint40))
Sell-side only, with the trail in [MIN_TRAIL_BPS, MAX_TRAIL_BPS].
| Parameter | Type | Description |
|---|---|---|
side | Side | Must be SellBase. |
amountIn | uint128 | Amount escrowed; greater than 0. |
param | uint128 | The trail, in bps: MIN_TRAIL_BPS (50) to MAX_TRAIL_BPS (5,000). |
| (unnamed) | uint16 | Unused by this type. |
| (unnamed) | uint40 | Unused by this type. |
| (unnamed) | uint40 | Unused by this type. |
| Returns | Type | Description |
|---|---|---|
| – | bool | Whether the parameters are valid. |
evaluate
function evaluate(Side, uint128 param, bytes32 state, uint256 oraclePrice) external pure returns (uint256 distanceBps, bytes32 newState)Raises the peak to the current price if higher, then is met when the price is at or below peak × (1 − trail).
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0xf25ecc56(evaluate(uint8,uint128,bytes32,uint256))
| Parameter | Type | Description |
|---|---|---|
| (unnamed) | Side | Unused by this type. |
param | uint128 | The trail, in bps. |
state | bytes32 | The peak price so far, as bytes32; zero before the first check. |
oraclePrice | uint256 | The Chainlink cross price for the market. |
| Returns | Type | Description |
|---|---|---|
distanceBps | uint256 | 0 when the trigger is met; otherwise the gap in bps of the price, at least 1. |
newState | bytes32 | The new peak, as bytes32. |
minOut
function minOut(Side, uint128, uint128, uint256) external pure returns (uint256)No extra floor, so the vault's own Chainlink floor applies.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0x2966791c(minOut(uint8,uint128,uint128,uint256))
| Parameter | Type | Description |
|---|---|---|
| (unnamed) | Side | Unused by this type. |
| (unnamed) | uint128 | Unused by this type. |
| (unnamed) | uint128 | Unused by this type. |
| (unnamed) | uint256 | Unused by this type. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Always 0. |
IOrderType
- Source:
packages/foundry/contracts/interfaces/IOrderType.sol - Interface
- Implemented by
LimitOrderType,StopOrderType,TrailingStopType
A stateless, view-only strategy for one kind of order (limit, stop-loss, trailing stop, …). The vault owns all order state and all funds; a strategy only reads what the vault passes and returns decisions. Because every function is pure and the vault reaches it with staticcall, a strategy can never write storage, move value, or reenter. The vault always enforces the guard and its own Chainlink-priced slippage floor on top of whatever a strategy returns, so a buggy or hostile strategy cannot fill an order at a bad price or past the guard — see minOut.
Functions
validate
function validate(Side side, uint128 amountIn, uint128 param, uint16 slippageBps, uint40 expiry, uint40 nowTs) external pure returns (bool ok)Validate placement parameters for this type. Returns false (or reverts) if invalid.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0x0956722c(validate(uint8,uint128,uint128,uint16,uint40,uint40))
| Parameter | Type | Description |
|---|---|---|
side | Side | Sell the base, or buy it. |
amountIn | uint128 | Amount escrowed. |
param | uint128 | The type's parameter: a trigger price for limit/stop, a trail in bps for trailing. |
slippageBps | uint16 | Maker's slippage tolerance. |
expiry | uint40 | Order expiry (unix seconds). |
nowTs | uint40 | Current block timestamp, passed in so the strategy stays pure. |
| Returns | Type | Description |
|---|---|---|
ok | bool | Whether the parameters are valid for this type. |
evaluate
function evaluate(Side side, uint128 param, bytes32 state, uint256 oraclePrice) external pure returns (uint256 distanceBps, bytes32 newState)The whole per-check decision, in one call so a check costs one staticcall.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0xf25ecc56(evaluate(uint8,uint128,bytes32,uint256))
| Parameter | Type | Description |
|---|---|---|
side | Side | Sell or buy. |
param | uint128 | The type parameter (see validate). |
state | bytes32 | This order's opaque per-type state (e.g. a trailing peak); zero for a new order. |
oraclePrice | uint256 | The Chainlink cross price for the market, in the market's price units. |
| Returns | Type | Description |
|---|---|---|
distanceBps | uint256 | 0 when the trigger is met (fill now); otherwise how far the price is from the trigger, which the vault turns into the next-check delay. Never 0 for an unmet trigger: the vault fills on 0, so use PriceMath.distanceBps, which rounds a sub-basis-point gap up to 1. |
newState | bytes32 | The state to persist; the vault writes it only when it differs from state. |
minOut
function minOut(Side side, uint128 amountIn, uint128 param, uint256 oraclePrice) external pure returns (uint256)An optional extra minimum-out floor, priced from Chainlink only. The vault takes the MAXIMUM of this and its own Chainlink floor (Chainlink value less the maker's slippage), so a strategy can only ever ask for MORE protection, never less. Return 0 to rely entirely on the vault's floor.
- Access: Anyone (read-only)
- Mutability:
pure - Selector:
0x2966791c(minOut(uint8,uint128,uint128,uint256))
| Parameter | Type | Description |
|---|---|---|
side | Side | Sell or buy. |
amountIn | uint128 | Amount escrowed. |
param | uint128 | The type parameter (see validate). |
oraclePrice | uint256 | The Chainlink cross price for the market. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | The floor, in the output token's raw units; 0 for none. |
MarketGuard
- Source:
packages/foundry/contracts/libraries/MarketGuard.sol - External library: deployed once and linked; its external functions run by DELEGATECALL in the caller's context
Decides whether a market is safe to fill: both Chainlink feeds must be valid and fresh, and the pool's TWAP must sit within the market's deviation limit of the Chainlink cross price.
An external library so the check is linked rather than inlined, keeping OrderVault under 24 KiB.
Constants
| Name | Declaration | Description |
|---|---|---|
MIN_TWAP_WINDOW | uint256 internal constant MIN_TWAP_WINDOW = 300 | Shortest twapWindow: a shorter window is close to spot price. |
MAX_TWAP_WINDOW | uint256 internal constant MAX_TWAP_WINDOW = 1 days | Longest twapWindow: a longer one outruns SaucerSwap's observation history. |
MIN_ORACLE_AGE | uint256 internal constant MIN_ORACLE_AGE = 60 | Shortest maxOracleAge. |
MAX_ORACLE_AGE | uint256 internal constant MAX_ORACLE_AGE = 26 hours | Longest maxOracleAge: Hedera's Chainlink feeds have a 24 h heartbeat; allow two hours of slack on top. |
MAX_DEVIATION_BPS | uint256 internal constant MAX_DEVIATION_BPS = 1_000 | Largest maxDeviationBps (10%). |
MAX_SLIPPAGE_BPS | uint256 internal constant MAX_SLIPPAGE_BPS = 1_000 | Largest maxSlippageBps (10%). |
Functions
paramsValid
function paramsValid(GuardParams calldata g, uint24 poolFee) external pure returns (bool)Whether guard parameters keep the guard meaningful. The owner can tune a market but can't switch its protection off: no near-spot TWAP, no unlimited oracle age, no unbounded deviation, and slippage must exceed the pool fee (or no order could ever fill) without exceeding 10%.
- Mutability:
pure - Visibility:
external - Used by:
MarketRegistry._validate
| Parameter | Type | Description |
|---|---|---|
g | GuardParams calldata | The guard settings: twapWindow 300 to 86,400 s, maxOracleAge 60 to 93,600 s, maxDeviationBps 1 to 1,000, and maxSlippageBps above poolFee / 100 and at most 1,000. |
poolFee | uint24 | The market pool's fee, in hundredths of a basis point. |
| Returns | Type | Description |
|---|---|---|
| – | bool | Whether every field is within its bounds. |
read
function read(Market storage m) external view returns (GuardReading memory r)The guard's reading for a market: the Chainlink cross price, the pool TWAP price and the verdict.
- Mutability:
view - Visibility:
external - Used by:
OrderVault.guardReading
A feed or pool call that reverts gives the matching GuardState instead of reverting. Checks run in order and stop at the first failure: feed validity, feed age, TWAP, deviation.
| Parameter | Type | Description |
|---|---|---|
m | Market storage | The market, in the vault's storage. |
| Returns | Type | Description |
|---|---|---|
r | GuardReading memory | The reading; see GuardReading. |
readFeed
function readFeed(IAggregatorV3 feed) internal view returns (uint256 answer, uint256 updatedAt)A feed's answer and update time, or zeros when the answer is unusable.
- Mutability:
view - Visibility:
internal - Used by:
MarketGuard.read
Unusable means the call reverted, the answer is zero or negative, or the update time is zero or in the future.
| Parameter | Type | Description |
|---|---|---|
feed | IAggregatorV3 | A Chainlink aggregator. |
| Returns | Type | Description |
|---|---|---|
answer | uint256 | The answer, in the feed's decimals; 0 when unusable. |
updatedAt | uint256 | The answer's update time (unix seconds); 0 when unusable. |
Inherited and imported
Part of this ABI but declared in SafeCast; the text is the upstream NatSpec.
SafeCastOverflowedIntToUint
error SafeCastOverflowedIntToUint(int256 value)- Declared in
SafeCast - Selector:
0xa8ce4432
An int value doesn't fit in a uint of bits size.
| Parameter | Type | Description |
|---|---|---|
value | int256 | – |
Other errors in this ABI: TickOutOfRange.
MarketRegistry
- Source:
packages/foundry/contracts/libraries/MarketRegistry.sol - External library: deployed once and linked; its external functions run by DELEGATECALL in the caller's context
Listing and tuning markets: the owner-only, once-per-market work of validating a market's guard and sweep settings, writing it to the vault's storage and associating the vault with its HTS tokens.
An external library (delegatecalled, like MarketGuard and Settlement), so this cold admin code lives outside OrderVault and no sweep, check or fill pays for it. The errors match the vault's, so callers see the same InvalidMarket / InvalidGuard / InvalidSweep whichever contract raises them.
Constants
| Name | Declaration | Description |
|---|---|---|
HTS | IHederaTokenService internal constant HTS = IHederaTokenService(address(0x167)) | The HTS system contract. |
MIN_SWEEP_INTERVAL | uint256 internal constant MIN_SWEEP_INTERVAL = 30 | Shortest minInterval. HIP-1215 caps expiry 62 days ahead; the minimum is a few seconds past consensus time. |
MAX_SWEEP_INTERVAL | uint256 internal constant MAX_SWEEP_INTERVAL = 1 days | Longest maxInterval. |
Functions
list
function list(Market storage m, Market calldata market) externalValidate market and write it to the empty slot m, reading the feeds' decimals and the pool's token order, then associate the vault with the market's HTS tokens.
- Mutability:
nonpayable - Visibility:
external - Used by:
OrderVault.listMarket
| Parameter | Type | Description |
|---|---|---|
m | Market storage | The vault's empty storage slot for the new market. |
market | Market calldata | The market to list; Market gives each field's bounds. |
Reverts:
InvalidMarket,InvalidGuardorInvalidSweepon a bad market.HtsError(Associate) if the vault cannot associate with a market token.
update
function update(Market storage m, GuardParams calldata guard, SweepParams calldata sweep, bool active) externalRetune a listed market's guard and sweep, or pause it. The bounds keep the guard from being switched off.
- Mutability:
nonpayable - Visibility:
external - Used by:
OrderVault.updateMarket
| Parameter | Type | Description |
|---|---|---|
m | Market storage | The listed market, in the vault's storage. |
guard | GuardParams calldata | New guard settings, checked against the market's stored poolFee. |
sweep | SweepParams calldata | New sweep settings. |
active | bool | Whether new orders may be placed. |
Reverts:
InvalidGuardorInvalidSweepon bad settings.
_validate
function _validate(GuardParams calldata g, SweepParams calldata p, uint24 poolFee) private pureThe bounds list and update enforce: the guard passes MarketGuard.paramsValid; minInterval is at least 30 s and at most maxInterval, which is at most 1 day; maxMoveBpsPerHour and maxOrders are non-zero; and maxFills is 1 to maxOrders.
- Mutability:
pure - Visibility:
private - Used by:
MarketRegistry.list,MarketRegistry.update
| Parameter | Type | Description |
|---|---|---|
g | GuardParams calldata | Guard settings. |
p | SweepParams calldata | Sweep settings. |
poolFee | uint24 | The market pool's fee, in hundredths of a basis point. |
Reverts:
InvalidGuardorInvalidSweepwhen a bound is broken.
Errors
InvalidMarket
error InvalidMarket()A zero pool, token or feed address, the same token twice, or two HBAR legs.
- Selector:
0x9db8d5b1
InvalidGuard
error InvalidGuard()Guard settings outside the MarketGuard.paramsValid bounds.
- Selector:
0x15e33ca3
InvalidSweep
error InvalidSweep()Sweep settings outside the SweepParams bounds.
- Selector:
0x3b77a1fd
OrderCollection
- Source:
packages/foundry/contracts/libraries/OrderCollection.sol - External library: deployed once and linked; its external functions run by DELEGATECALL in the caller's context
Creates the HTS NFT collection whose serial numbers are order ids.
An external library, linked rather than inlined, so this one-time setup doesn't count against OrderVault's 24 KiB limit. It runs by DELEGATECALL, so the vault is the caller HTS sees.
Constants
| Name | Declaration | Description |
|---|---|---|
HTS | IHederaTokenService internal constant HTS = IHederaTokenService(address(0x167)) | The HTS system contract. |
HTS_SUCCESS | int64 internal constant HTS_SUCCESS = 22 | HTS response code for success. |
KEYS_SUPPLY_AND_WIPE | uint256 internal constant KEYS_SUPPLY_AND_WIPE = 16 | 8 | HTS key-type bits for the supply (16) and wipe (8) keys. |
AUTO_RENEW_PERIOD | int64 internal constant AUTO_RENEW_PERIOD = 7_776_000 | The collection's auto-renew period, in seconds (90 days). |
Functions
create
function create(string calldata name, string calldata symbol, uint256 fee) external returns (int64 rc, address collection)Create the collection with the vault as treasury and holder of the supply and wipe keys.
- Mutability:
nonpayable - Visibility:
external - Used by:
OrderVault.initialize
| Parameter | Type | Description |
|---|---|---|
name | string calldata | Collection name. |
symbol | string calldata | Collection symbol. |
fee | uint256 | HBAR (tinybar) forwarded as the HTS creation fee; any excess stays in the vault. |
| Returns | Type | Description |
|---|---|---|
rc | int64 | The HTS response code. |
collection | address | The new token's address, or zero on failure. |
Settlement
- Source:
packages/foundry/contracts/libraries/Settlement.sol - External library: deployed once and linked; its external functions run by DELEGATECALL in the caller's context
The SaucerSwap swap, the HTS token and order-NFT operations, and ERC-20 moves. It is an external library (its own deployed code, linked like MarketGuard/OrderCollection), so this call-encoding-heavy code lives outside OrderVault and the vault stays under the 24 KB limit with room to spare. The vault keeps the readable sweep → evaluate → guard → fill flow and calls here only for the external interactions; it still enforces the guard and its own Chainlink slippage floor before any swap.
Constants
| Name | Declaration | Description |
|---|---|---|
HTS_SUCCESS | int64 internal constant HTS_SUCCESS = 22 | HTS response code for success. |
HTS_ALREADY_ASSOCIATED | int64 internal constant HTS_ALREADY_ASSOCIATED = 194 | HTS response code for a token already associated with the account. |
HBAR | address internal constant HBAR = address(0) | Stands for HBAR in token arguments. |
SWAP_DEADLINE | uint256 internal constant SWAP_DEADLINE = 300 | Seconds a swap stays valid: its router deadline. |
Functions
swap
function swap(ISaucerSwapV2Router router, address whbar, uint24 poolFee, address tokenIn, address tokenOut, uint256 amountIn, uint256 minOut) public returns (uint256 amountOut)Swap amountIn of tokenIn for tokenOut on SaucerSwap V2, requiring at least minOut. For an HBAR leg, WHBAR is used and the router wraps/unwraps. The caller has already checked escrow and set minOut from Chainlink, so the swap's own amountOutMinimum is the final price protection.
- Mutability:
nonpayable - Visibility:
public - Used by:
OrderVault._swap
| Parameter | Type | Description |
|---|---|---|
router | ISaucerSwapV2Router | The SaucerSwap V2 SwapRouter. |
whbar | address | The WHBAR token, substituted for an HBAR leg. |
poolFee | uint24 | The pool's fee, in hundredths of a basis point. |
tokenIn | address | Input token; address(0) for HBAR. |
tokenOut | address | Output token; address(0) for HBAR. |
amountIn | uint256 | Input amount, in raw units. |
minOut | uint256 | Smallest acceptable output, in raw units. |
| Returns | Type | Description |
|---|---|---|
amountOut | uint256 | Output received, in raw units. |
Reverts:
TransferRejectedif approving the router for a token input returns false. The router reverts if the output is belowminOut.
mintNft
function mintNft(IHederaTokenService hts, address collection, address to) public returns (uint256 orderId)Mint one order NFT in collection and transfer it to to. The serial is the order id.
- Mutability:
nonpayable - Visibility:
public - Used by:
OrderVault._mintOrderNft
| Parameter | Type | Description |
|---|---|---|
hts | IHederaTokenService | The HTS system contract. |
collection | address | The order NFT collection. |
to | address | The maker. |
| Returns | Type | Description |
|---|---|---|
orderId | uint256 | The minted serial number. |
Reverts:
HtsError(MintorTransferNft) if HTS refuses either step.
retireNft
function retireNft(IHederaTokenService hts, address collection, uint256 orderId, address holder) public returns (int64 rc)Retire a settled order's NFT (burn if the vault holds it, else wipe from the holder). Never reverts; returns the response code so the vault can report a failure through an event without blocking settle.
- Mutability:
nonpayable - Visibility:
public - Used by:
OrderVault._retireNft
| Parameter | Type | Description |
|---|---|---|
hts | IHederaTokenService | The HTS system contract. |
collection | address | The order NFT collection. |
orderId | uint256 | The order's serial number. |
holder | address | The NFT's current holder. |
| Returns | Type | Description |
|---|---|---|
rc | int64 | The HTS response code (22 is success). |
associate
function associate(IHederaTokenService hts, address token) publicAssociate the vault with an HTS token (idempotent).
- Mutability:
nonpayable - Visibility:
public - Used by:
MarketRegistry.list
| Parameter | Type | Description |
|---|---|---|
hts | IHederaTokenService | The HTS system contract. |
token | address | The token. |
Reverts:
HtsError(Associate) unless HTS answers success (22) or already associated (194).
pullToken
function pullToken(address token, address from, address to, uint256 amount) public returns (bool)Pull amount of token from from to the vault; returns false on a failed or false-returning move.
- Mutability:
nonpayable - Visibility:
public - Used by:
OrderVault._pullToken
| Parameter | Type | Description |
|---|---|---|
token | address | The token. |
from | address | The owner, who must have approved the vault. |
to | address | The recipient (the vault). |
amount | uint256 | Amount, in raw units. |
| Returns | Type | Description |
|---|---|---|
| – | bool | Whether the transfer succeeded. |
transferToken
function transferToken(address token, address to, uint256 amount) public returns (bool)Send amount of token to to; returns false on a failed or false-returning move.
- Mutability:
nonpayable - Visibility:
public - Used by:
OrderVault._transferToken
| Parameter | Type | Description |
|---|---|---|
token | address | The token. |
to | address | The recipient. |
amount | uint256 | Amount, in raw units. |
| Returns | Type | Description |
|---|---|---|
| – | bool | Whether the transfer succeeded. |
Errors
TransferRejected
error TransferRejected()Approving the router for the input token returned false.
- Selector:
0x4e472e5e
Other errors in this ABI: HtsError.
SweepMath
- Source:
packages/foundry/contracts/libraries/SweepMath.sol - Internal library: compiled into each contract that uses it
One copy of every number the vault charges or schedules by, shared by OrderVault (which acts on it) and OrderVaultLens (which previews it). Internal functions only, so it is compiled into both and adds no call overhead; a lens preview and the vault's own charge come from the same code.
Gas figures come from Costs (measured on testnet, see MarketConfig.costs()); rate is tinybar per RATE_UNIT tinycents from the 0x168 exchange-rate system contract, read once per call by the caller.
Constants
| Name | Declaration | Description |
|---|---|---|
RATE_UNIT | uint256 internal constant RATE_UNIT = 1e12 | Tinycents converted per exchange-rate lookup. |
MIN_CHECKS_FUNDED | uint256 internal constant MIN_CHECKS_FUNDED = 6 | Solo checks a new order must be able to pay for on top of its reserve. |
SWEEP_GRACE | uint256 internal constant SWEEP_GRACE = 120 | A sweep that has not fired this long after its expiry is treated as dead and may be restarted. |
Functions
gasToTinybar
function gasToTinybar(Costs memory c, uint256 gas, uint256 rate) internal pure returns (uint256)Tinybar for gas at the configured gas price plus the safety margin.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault._visit,OrderVault._finish,OrderVault._ensureSweep,OrderVault._payerFloat,OrderVaultLens.payerFloat,SweepMath.sweepShare,SweepMath.reserve,SweepMath.batchCharges
| Parameter | Type | Description |
|---|---|---|
c | Costs memory | The vault's costs. |
gas | uint256 | Gas units. |
rate | uint256 | Tinybar per RATE_UNIT tinycents, from the 0x168 exchange-rate system contract. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Tinybar. |
sweepShare
function sweepShare(Costs memory c, uint256 fundedOrders, uint256 rate) internal pure returns (uint256)Per-order charge for one scheduled check: an even share of the sweep's fixed cost plus its own check.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault.topUp,OrderVaultLens.checkCost,OrderVaultLens.checkCostShared,SweepMath.minBudget,SweepMath.batchCharges
| Parameter | Type | Description |
|---|---|---|
c | Costs memory | The vault's costs. |
fundedOrders | uint256 | Orders sharing the fixed cost; at least 1 (pass 1 for a solo check). |
rate | uint256 | Tinybar per RATE_UNIT tinycents, from the 0x168 exchange-rate system contract. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Tinybar per order. |
fillGas
function fillGas(Costs memory c, bool hbarIn) internal pure returns (uint256)Gas to fill and settle one order whose input is HBAR (hbarIn) or an HTS token.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault._visit,SweepMath.reserve
| Parameter | Type | Description |
|---|---|---|
c | Costs memory | The vault's costs. |
hbarIn | bool | Whether the order's input is HBAR. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Gas units. |
tailGas
function tailGas(Costs memory c) internal pure returns (uint256)The most one order can owe for the chain's final sweep: running it alone, with no reschedule.
- Mutability:
pure - Visibility:
internal - Used by:
SweepMath.reserve
| Parameter | Type | Description |
|---|---|---|
c | Costs memory | The vault's costs. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Gas units. |
finishGas
function finishGas(Costs memory c) internal pure returns (uint256)Gas a sweep keeps back so it can always reach the reschedule.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault.sweep,SweepMath.sweepGasLimit
| Parameter | Type | Description |
|---|---|---|
c | Costs memory | The vault's costs. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Gas units. |
reserve
function reserve(Costs memory c, bool hbarIn, uint256 rate) internal pure returns (uint256)Budget an order never spends on routine checks: its fill, plus its share of a final sweep.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault._reserve,OrderVaultLens.fillCost,OrderVaultLens.previewCharges,SweepMath.minBudget
| Parameter | Type | Description |
|---|---|---|
c | Costs memory | The vault's costs. |
hbarIn | bool | Whether the order's input is HBAR. |
rate | uint256 | Tinybar per RATE_UNIT tinycents, from the 0x168 exchange-rate system contract. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Tinybar. |
minBudget
function minBudget(Costs memory c, bool hbarIn, uint256 rate) internal pure returns (uint256)Smallest budget accepted at placement: the reserve plus MIN_CHECKS_FUNDED solo checks.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault.placeOrder,OrderVaultLens.minBudget
| Parameter | Type | Description |
|---|---|---|
c | Costs memory | The vault's costs. |
hbarIn | bool | Whether the order's input is HBAR. |
rate | uint256 | Tinybar per RATE_UNIT tinycents, from the 0x168 exchange-rate system contract. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Tinybar. |
sweepGasLimit
function sweepGasLimit(Costs memory c, SweepParams memory sp, uint256 openOrders) internal pure returns (uint256)Gas limit for a sweep of a market with openOrders open orders: every order it will visit, and as many fills as it may make, priced at the costlier token-in fill.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault._sweepGasLimit,OrderVaultLens.sweepGasLimit
| Parameter | Type | Description |
|---|---|---|
c | Costs memory | The vault's costs. |
sp | SweepParams memory | The market's sweep settings. |
openOrders | uint256 | The market's open orders. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Gas units. |
delayFor
function delayFor(SweepParams memory sp, uint256 distanceBps, uint256 expiry, uint256 nowTs) internal pure returns (uint256 d)Seconds to wait before the next check of an order distanceBps from its trigger: as long as the price could plausibly need to cover that distance, within the market's bounds, and never past the order's expiry (so expired orders are refunded promptly).
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault._delayFor,OrderVaultLens.nextCheckDelay,OrderVaultLens.orderNextCheckDelay
| Parameter | Type | Description |
|---|---|---|
sp | SweepParams memory | The market's sweep settings. |
distanceBps | uint256 | The order's distance from its trigger, in bps. |
expiry | uint256 | The order's expiry (unix seconds). |
nowTs | uint256 | The current block timestamp. |
| Returns | Type | Description |
|---|---|---|
d | uint256 | Seconds: distanceBps × 3,600 / maxMoveBpsPerHour, capped at maxInterval and at the time left to expiry, and never below minInterval. |
isDead
function isDead(address pendingSchedule, uint256 nextSweepAt, uint256 nowTs) internal pure returns (bool)Whether a market's sweep chain has stopped: nothing pending, or the pending one is long overdue.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault._sweepIsDead,OrderVaultLens.sweepStatus
| Parameter | Type | Description |
|---|---|---|
pendingSchedule | address | The pending schedule's address; zero when none. |
nextSweepAt | uint256 | When the pending sweep is due (unix seconds). |
nowTs | uint256 | The current block timestamp. |
| Returns | Type | Description |
|---|---|---|
| – | bool | True when nothing is pending or nowTs is more than SWEEP_GRACE (120 s) past nextSweepAt. |
batchCharges
function batchCharges(Costs memory c, uint256 rate, ChargeInput[] memory orders) internal pure returns (uint256 share, uint256 parkFee)Charges for one scheduled sweep of orders. share is each paying order's part: the fixed cost split over the live orders that can afford it (recounted until stable) plus its own check. Orders that can't afford it pay parkFee from their reserve: their own check, and when nobody can pay, an even part of this final sweep too.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault._batchCharges,OrderVaultLens.previewCharges
| Parameter | Type | Description |
|---|---|---|
c | Costs memory | The vault's costs. |
rate | uint256 | Tinybar per RATE_UNIT tinycents, from the 0x168 exchange-rate system contract. |
orders | ChargeInput[] memory | The batch's orders. |
| Returns | Type | Description |
|---|---|---|
share | uint256 | Tinybar charged to each order that can pay. |
parkFee | uint256 | Tinybar charged to each order that is parked. |
Types
ChargeInput
struct ChargeInput {
bool live;
uint256 budget;
uint256 reserve;
}What the batch charge needs to know about one order in a sweep's batch.
| Field | Type | Description |
|---|---|---|
live | bool | Open, funded and not expired. |
budget | uint256 | The order's budget, in tinybar. |
reserve | uint256 | reserve() for the order's side, in tinybar. |
PriceMath
- Source:
packages/foundry/contracts/libraries/PriceMath.sol - Internal library: compiled into each contract that uses it
Prices are "quote per 1 base" with 8 decimals, the same scale as Chainlink USD feeds.
Constants
| Name | Declaration | Description |
|---|---|---|
PRICE_SCALE | uint256 internal constant PRICE_SCALE = 1e8 | Prices carry 8 decimals. |
BPS | uint256 internal constant BPS = 10_000 | Basis points in 1. |
RAY | uint256 internal constant RAY = 1e27 | 27-decimal fixed point for the tick math. |
TICK_BASE_RAY | uint256 internal constant TICK_BASE_RAY = 1_000_100_000_000_000_000_000_000_000 | 1.0001 in RAY: the price ratio between adjacent Uniswap-v3 style ticks. |
MAX_TICK | int24 internal constant MAX_TICK = 887_272 | Uniswap v3 tick bounds; pools never report a tick outside them. |
Functions
powRay
function powRay(uint256 exponent) internal pure returns (uint256 result)1.0001^exponent in RAY, by binary exponentiation (relative error below 1e-10 across the tick range).
- Mutability:
pure - Visibility:
internal - Used by:
PriceMath.tickToPrice
| Parameter | Type | Description |
|---|---|---|
exponent | uint256 | The power, at most MAX_TICK in practice. |
| Returns | Type | Description |
|---|---|---|
result | uint256 | 1.0001^exponent, scaled by 1e27. |
meanTick
function meanTick(int56 cumulativeStart, int56 cumulativeEnd, uint32 window) internal pure returns (int24)Arithmetic-mean tick between two cumulative readings, rounded towards negative infinity.
- Mutability:
pure - Visibility:
internal - Used by:
MarketGuard.read
| Parameter | Type | Description |
|---|---|---|
cumulativeStart | int56 | The tick cumulative at the start of the window. |
cumulativeEnd | int56 | The tick cumulative at the end of the window. |
window | uint32 | The window, in seconds; non-zero. |
| Returns | Type | Description |
|---|---|---|
| – | int24 | The mean tick. |
tickToPrice
function tickToPrice(int24 tick, bool baseIsToken0, uint8 baseDecimals, uint8 quoteDecimals) internal pure returns (uint256)Pool price as "quote per 1 base" (8 decimals) from a tick, which prices token1 in token0.
- Mutability:
pure - Visibility:
internal - Used by:
MarketGuard.read
Raw quote per raw base is 1.0001^tick when base is token0 and 1.0001^-tick otherwise. Picking the sign first means one division at full precision. A price too small to represent returns 0, which the guard treats as maximal deviation.
| Parameter | Type | Description |
|---|---|---|
tick | int24 | A pool tick, within plus or minus MAX_TICK (887,272). |
baseIsToken0 | bool | Whether the base is the pool's token0. |
baseDecimals | uint8 | The base token's decimals. |
quoteDecimals | uint8 | The quote token's decimals. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Quote per 1 base, 8 decimals. |
Reverts:
TickOutOfRangeiftickis outside plus or minusMAX_TICK.
crossPrice
function crossPrice(uint256 baseUsd, uint8 baseFeedDecimals, uint256 quoteUsd, uint8 quoteFeedDecimals) internal pure returns (uint256)Cross price of base in quote (8 decimals) from two USD feeds.
- Mutability:
pure - Visibility:
internal - Used by:
MarketGuard.read
| Parameter | Type | Description |
|---|---|---|
baseUsd | uint256 | The base/USD answer. |
baseFeedDecimals | uint8 | The base feed's decimals. |
quoteUsd | uint256 | The quote/USD answer; non-zero. |
quoteFeedDecimals | uint8 | The quote feed's decimals. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Quote per 1 base, 8 decimals. |
baseToQuote
function baseToQuote(uint256 baseAmount, uint256 price, uint8 baseDecimals, uint8 quoteDecimals) internal pure returns (uint256)Quote amount (raw units) worth baseAmount raw base at price.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault._valueAt
| Parameter | Type | Description |
|---|---|---|
baseAmount | uint256 | Base amount, in raw units. |
price | uint256 | Quote per 1 base, 8 decimals. |
baseDecimals | uint8 | The base token's decimals. |
quoteDecimals | uint8 | The quote token's decimals. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Quote amount, in raw units, rounded down. |
quoteToBase
function quoteToBase(uint256 quoteAmount, uint256 price, uint8 baseDecimals, uint8 quoteDecimals) internal pure returns (uint256)Base amount (raw units) worth quoteAmount raw quote at price.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault._valueAt
| Parameter | Type | Description |
|---|---|---|
quoteAmount | uint256 | Quote amount, in raw units. |
price | uint256 | Quote per 1 base, 8 decimals; non-zero. |
baseDecimals | uint8 | The base token's decimals. |
quoteDecimals | uint8 | The quote token's decimals. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | Base amount, in raw units, rounded down. |
deviationBps
function deviationBps(uint256 a, uint256 b) internal pure returns (uint256)|a - b| / reference, in basis points.
- Mutability:
pure - Visibility:
internal - Used by:
MarketGuard.read,PriceMath.distanceBps
| Parameter | Type | Description |
|---|---|---|
a | uint256 | The value compared. |
b | uint256 | The reference; non-zero. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | The difference in bps of b, rounded down. |
distanceBps
function distanceBps(uint256 trigger, uint256 price) internal pure returns (uint256)How far price is from a trigger it has NOT met, in bps of price, and never less than 1. An order type returns 0 only for a met trigger, because the vault fills on 0: deviationBps rounds down, so a price a fraction of a basis point short of its trigger would otherwise read as met and fill early.
- Mutability:
pure - Visibility:
internal - Used by:
LimitOrderType.evaluate,StopOrderType.evaluate,TrailingStopType.evaluate
| Parameter | Type | Description |
|---|---|---|
trigger | uint256 | The trigger price. |
price | uint256 | The current price; non-zero. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | The distance in bps of price, at least 1. |
lessBps
function lessBps(uint256 amount, uint256 bps) internal pure returns (uint256)amount reduced by bps basis points, rounded down.
- Mutability:
pure - Visibility:
internal - Used by:
OrderVault.fillFromVault
| Parameter | Type | Description |
|---|---|---|
amount | uint256 | The amount. |
bps | uint256 | Basis points to take off, at most 10,000. |
| Returns | Type | Description |
|---|---|---|
| – | uint256 | The reduced amount. |
Errors
TickOutOfRange
error TickOutOfRange(int24 tick)A tick outside the Uniswap v3 range of plus or minus 887,272.
- Selector:
0xdd455374
| Parameter | Type | Description |
|---|---|---|
tick | int24 | The tick given. |
Shared types
- Source:
packages/foundry/contracts/types/OrderTypes.sol
File-level structs, enums and errors used across the contracts above.
Types
Side
enum Side {
SellBase,
BuyBase
}Which way an order trades.
| Value | Name | Description |
|---|---|---|
| 0 | SellBase | Sell amountIn of the base token for the quote token. |
| 1 | BuyBase | Spend amountIn of the quote token on the base token. |
Trigger
enum Trigger {
AtOrAbove,
AtOrBelow
}Not used by the vault or the shipped order types since v1.1, where the order type encodes the direction; kept for the tests that drive the earlier fixed-trigger vault.
Sell + AtOrAbove is a limit sell, Sell + AtOrBelow a stop-loss, Buy + AtOrBelow a limit buy, Buy + AtOrAbove a stop-buy.
| Value | Name | Description |
|---|---|---|
| 0 | AtOrAbove | Fires when the price is at or above the trigger. |
| 1 | AtOrBelow | Fires when the price is at or below the trigger. |
Status
enum Status {
None,
Open,
Filled,
Cancelled,
Expired
}An order's lifecycle state.
| Value | Name | Description |
|---|---|---|
| 0 | None | No order with this id. |
| 1 | Open | Escrowed and waiting for its trigger. |
| 2 | Filled | Swapped; the output was paid to the NFT holder (or credited for claim). |
| 3 | Cancelled | Cancelled by its holder; escrow and unused budget refunded. |
| 4 | Expired | Reached its expiry unfilled; escrow and unused budget refunded. |
HtsOperation
enum HtsOperation {
CreateCollection,
Mint,
TransferNft,
Associate
}Which HTS operation failed, for the shared HtsError.
| Value | Name | Description |
|---|---|---|
| 0 | CreateCollection | Creating the order NFT collection in initialize. |
| 1 | Mint | Minting an order NFT in placeOrder. |
| 2 | TransferNft | Moving a newly minted order NFT from the vault to the maker. |
| 3 | Associate | Associating the vault with a market's HTS token in listMarket. |
GuardState
enum GuardState {
Open,
OracleInvalid,
OracleStale,
TwapUnavailable,
DeviationTooHigh
}The guard's verdict on a market, from MarketGuard.read. Only Open lets an order fill.
| Value | Name | Description |
|---|---|---|
| 0 | Open | Both feeds are valid and fresh and the pool TWAP is within maxDeviationBps of Chainlink. |
| 1 | OracleInvalid | A feed reverted, answered zero or less, or reported a zero or future update time. |
| 2 | OracleStale | The older feed update is more than maxOracleAge seconds old. |
| 3 | TwapUnavailable | The pool could not report a TWAP over twapWindow (too little observation history). |
| 4 | DeviationTooHigh | The pool TWAP is more than maxDeviationBps away from the Chainlink cross price. |
Market
struct Market {
address base;
address quote;
uint8 baseDecimals;
uint8 quoteDecimals;
bool baseIsHbar;
bool quoteIsHbar;
IAggregatorV3 baseFeed;
IAggregatorV3 quoteFeed;
uint8 baseFeedDecimals;
uint8 quoteFeedDecimals;
ISaucerSwapV2Pool pool;
uint24 poolFee;
bool baseIsToken0;
bool active;
GuardParams guard;
SweepParams sweep;
}A tradable pair. Prices are quote per 1 base, 8 decimals.
| Field | Type | Description |
|---|---|---|
base | address | Base token address (an HTS token; the WHBAR token when baseIsHbar). Non-zero, distinct from quote. |
quote | address | Quote token address (an HTS token; the WHBAR token when quoteIsHbar). Non-zero. |
baseDecimals | uint8 | The base token's decimals (8 for HBAR). |
quoteDecimals | uint8 | The quote token's decimals. |
baseIsHbar | bool | The base leg is native HBAR: escrow and payouts in HBAR, routed through WHBAR. |
quoteIsHbar | bool | The quote leg is native HBAR. At most one of the two legs may be HBAR. |
baseFeed | IAggregatorV3 | Chainlink base/USD feed. Non-zero. |
quoteFeed | IAggregatorV3 | Chainlink quote/USD feed. Non-zero. |
baseFeedDecimals | uint8 | Read from baseFeed.decimals() by listMarket; the value passed in is ignored. |
quoteFeedDecimals | uint8 | Read from quoteFeed.decimals() by listMarket; the value passed in is ignored. |
pool | ISaucerSwapV2Pool | SaucerSwap V2 pool for the pair, used for the TWAP and the swap. Non-zero. |
poolFee | uint24 | The pool's fee in hundredths of a basis point (3000 = 0.30%); poolFee / 100 is the slippage floor, in bps, that every order must exceed. |
baseIsToken0 | bool | Set by listMarket from pool.token0(); the value passed in is ignored. |
active | bool | Whether new orders may be placed. listMarket sets it to true (the value passed in is ignored); updateMarket changes it. |
guard | GuardParams | The guard's bounds; see GuardParams. |
sweep | SweepParams | The sweep's schedule and batch limits; see SweepParams. |
GuardParams
struct GuardParams {
uint32 twapWindow;
uint16 maxDeviationBps;
uint32 maxOracleAge;
uint16 maxSlippageBps;
}A market's guard settings. MarketGuard.paramsValid bounds every field so the guard can't be switched off.
| Field | Type | Description |
|---|---|---|
twapWindow | uint32 | Seconds of pool TWAP compared with Chainlink: 300 to 86,400 (5 minutes to 1 day). |
maxDeviationBps | uint16 | Largest TWAP-to-Chainlink gap, in bps, at which a fill may proceed: 1 to 1,000. |
maxOracleAge | uint32 | Oldest acceptable feed update, in seconds: 60 to 93,600 (26 hours). |
maxSlippageBps | uint16 | Largest slippage an order may set, in bps: above poolFee / 100 and at most 1,000. |
SweepParams
struct SweepParams {
uint32 minInterval;
uint32 maxInterval;
uint16 maxMoveBpsPerHour;
uint16 maxOrders;
uint8 maxFills;
}How often a market's sweep runs. The next sweep waits roughly as long as the price would need to reach the nearest trigger at maxMoveBpsPerHour, clamped to [minInterval, maxInterval].
| Field | Type | Description |
|---|---|---|
minInterval | uint32 | Shortest wait between sweeps, in seconds: at least 30 and at most maxInterval. |
maxInterval | uint32 | Longest wait between sweeps, in seconds: at most 86,400 (1 day). |
maxMoveBpsPerHour | uint16 | The price move per hour, in bps, the schedule assumes. Greater than 0. |
maxOrders | uint16 | Open orders one sweep visits, from a rotating cursor. Greater than 0. |
maxFills | uint8 | Fills one sweep may make: 1 to maxOrders. |
SweepState
struct SweepState {
address pendingSchedule;
uint40 nextSweepAt;
uint32 cursor;
uint32 fundedOrders;
uint32 epoch;
uint8 heldStreak;
}A market's sweep chain, as stored by the vault (sweeps(marketId)).
| Field | Type | Description |
|---|---|---|
pendingSchedule | address | The HSS schedule of the next sweep; zero when none is pending. |
nextSweepAt | uint40 | When the pending sweep is due (unix seconds). |
cursor | uint32 | Index in the market's open-order list where the next batch starts. |
fundedOrders | uint32 | Open orders whose budget still pays for checks; the chain keeps running while it is above 0. |
epoch | uint32 | Bumped on every new schedule; a scheduled sweep carrying an older epoch has been superseded. |
heldStreak | uint8 | Consecutive sweeps where a triggered order could not fill (at most 8); drives the back-off. |
SweepStatus
enum SweepStatus {
Idle,
Scheduled,
Stalled
}What OrderVaultLens.sweepStatus reports for a market.
| Value | Name | Description |
|---|---|---|
| 0 | Idle | No funded orders, so no sweep is needed. |
| 1 | Scheduled | A sweep is pending and not overdue. |
| 2 | Stalled | Funded orders are waiting but no sweep will fire; anyone may call restartSweep. |
Costs
struct Costs {
uint32 scheduleGas;
uint32 sweepBaseGas;
uint32 checkGas;
uint32 fillGasHbarIn;
uint32 fillGasTokenIn;
uint32 settleGas;
uint32 idleSweepGas;
uint32 gasPriceTinycents;
uint16 safetyBps;
}Gas used by each piece of work, measured on Hedera testnet, and the network gas price.
| Field | Type | Description |
|---|---|---|
scheduleGas | uint32 | The HSS scheduling fee, as gas. Non-zero. |
sweepBaseGas | uint32 | A sweep's fixed gas besides scheduling and its orders. |
checkGas | uint32 | Gas to check one order. Non-zero. |
fillGasHbarIn | uint32 | Gas to fill an order whose input is HBAR, before settlement. Non-zero. |
fillGasTokenIn | uint32 | Gas to fill an order whose input is an HTS token, before settlement. Non-zero. |
settleGas | uint32 | Gas to settle one order (payouts and retiring its NFT); added to every fill and expiry. |
idleSweepGas | uint32 | A sweep that finds nothing to do: superseded by an earlier one, or left with no funded orders. |
gasPriceTinycents | uint32 | Hedera prices gas in USD; converted to tinybar through the 0x168 exchange-rate contract. Non-zero. |
safetyBps | uint16 | Margin added to every gas-to-HBAR conversion, in bps: 0 to 10,000. |
Order
struct Order {
uint32 marketId;
Side side;
uint8 orderType;
Status status;
bool funded;
uint16 slippageBps;
uint40 createdAt;
uint40 expiry;
uint128 amountIn;
uint128 typeParam;
uint128 budget;
bytes32 typeState;
}One order, as stored by the vault (getOrder(orderId)). The order id is its NFT serial number.
| Field | Type | Description |
|---|---|---|
marketId | uint32 | The market it trades on. |
side | Side | Sell the base, or buy it. |
orderType | uint8 | Index into the vault's order-type registry (limit, stop, trailing, …). |
status | Status | Lifecycle state. |
funded | bool | Whether its budget still pays for scheduled checks. A parked order is not checked until topUp. |
slippageBps | uint16 | The maker's slippage tolerance, in bps. |
createdAt | uint40 | Placement time (unix seconds). |
expiry | uint40 | Expiry time (unix seconds); the order is refunded at the first check at or after it. |
amountIn | uint128 | Escrowed input amount, in the input token's raw units (tinybar for HBAR). |
typeParam | uint128 | The type's parameter: a trigger price for limit/stop, a trail in bps for trailing. |
budget | uint128 | Unspent HBAR (tinybar) prepaid for checks and the fill. |
typeState | bytes32 | The type's opaque per-order state (e.g. a trailing peak); zero for stateless types. |
PlaceParams
struct PlaceParams {
uint32 marketId;
Side side;
uint8 orderType;
uint128 amountIn;
uint128 typeParam;
uint16 slippageBps;
uint40 expiry;
}The arguments of placeOrder.
| Field | Type | Description |
|---|---|---|
marketId | uint32 | A listed, active market. |
side | Side | Sell the base, or buy it. The input token is the base for SellBase and the quote for BuyBase. |
orderType | uint8 | A registered, active order-type id. The deploy script registers limit as 0, stop as 1 and trailing stop as 2. |
amountIn | uint128 | Amount to escrow, in the input token's raw units (tinybar for HBAR). Greater than 0. |
typeParam | uint128 | For limit and stop orders, the trigger price (quote per 1 base, 8 decimals), greater than 0. For a trailing stop (sell-side only), the trail in bps, 50 to 5,000. |
slippageBps | uint16 | Slippage tolerance, in bps: above the market's poolFee / 100 and at most its guard.maxSlippageBps. |
expiry | uint40 | Expiry time (unix seconds): after the current block and at most 90 days ahead. |
GuardReading
struct GuardReading {
GuardState state;
uint256 oraclePrice;
uint256 poolPrice;
uint256 deviationBps;
uint256 oracleUpdatedAt;
}A market's guard reading, from guardReading(marketId).
| Field | Type | Description |
|---|---|---|
state | GuardState | The verdict; only Open lets an order fill. |
oraclePrice | uint256 | Chainlink cross price, quote per 1 base with 8 decimals; 0 when the state is OracleInvalid. |
poolPrice | uint256 | Pool TWAP price in the same units; 0 unless the TWAP was read. |
deviationBps | uint256 | Gap between poolPrice and oraclePrice, in bps of oraclePrice; 0 unless computed. |
oracleUpdatedAt | uint256 | The older of the two feeds' update times (unix seconds); 0 when the state is OracleInvalid. |
Errors
HtsError
error HtsError(HtsOperation operation, int64 responseCode)An HTS system-contract call returned a non-success response code. Shared by the vault and the Settlement library so both can revert and callers can catch the same error.
- Selector:
0x6df6d223
| Parameter | Type | Description |
|---|---|---|
operation | HtsOperation | The HTS operation that failed. |
responseCode | int64 | The HTS response code it returned (22 is success). |
From docs/CONTRACT-API.md at v1.1 (cee2d4e) · View source