Contract API

Generated by node scripts/gen-contract-api.mjs from 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

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

NameDeclarationDescription
ROUTERISaucerSwapV2Router public immutable ROUTERThe SaucerSwap V2 SwapRouter every fill swaps through.
WHBARaddress public immutable WHBARThe WHBAR HTS token, used as the HBAR leg of swap routes.
collectionaddress public collectionHTS NFT collection whose serial numbers are order ids.
costsCosts public costsGas figures and gas price the vault charges and schedules by; see Costs.
marketCountuint32 public marketCountNumber of listed markets. Market ids run from 1 to marketCount.
sweepsmapping(uint256 marketId => SweepState) public sweepsEach market's sweep chain; see SweepState.
orderTypesmapping(uint8 id => address impl) public orderTypesThe 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.
orderTypeActivemapping(uint8 id => bool active) public orderTypeActiveWhether new orders may use order type id.
orderTypeCountuint8 public orderTypeCountNumber of registered order types. Ids run from 0 to orderTypeCount - 1.
escrowedmapping(address token => uint256) public escrowedTokens held on behalf of open orders, keyed by token (address(0) is HBAR).
totalBudgetsuint256 public totalBudgetsHBAR prepaid for scheduled checks and fills of open orders.
creditsmapping(address account => mapping(address token => uint256)) public creditsPayouts that could not be delivered and wait for claim.
totalCreditsmapping(address token => uint256) public totalCreditsSum 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
ParameterTypeDescription
owner_addressInitial owner (Ownable2Step). Non-zero.
router_ISaucerSwapV2RouterSaucerSwap V2 SwapRouter.
whbar_addressWHBAR HTS token, used as the HBAR leg of routes.
costs_Costs memoryInitial costs; same bounds as setCosts.

Reverts:

initialize

function initialize(string calldata name, string calldata symbol) external payable onlyOwner

Create 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.

ParameterTypeDescription
namestring calldataCollection name.
symbolstring calldataCollection symbol.

Reverts:

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))))
ParameterTypeDescription
marketMarket calldataThe market; Market, GuardParams and SweepParams give each field's bounds.
ReturnsTypeDescription
marketIduint256The new market's id; ids start at 1.

Reverts:

updateMarket

function updateMarket(uint256 marketId, GuardParams calldata guard, SweepParams calldata sweepParams, bool active) external onlyOwner

Tune 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))
ParameterTypeDescription
marketIduint256A listed market.
guardGuardParams calldataNew guard settings (bounds in GuardParams); the slippage floor uses the stored poolFee.
sweepParamsSweepParams calldataNew sweep settings (bounds in SweepParams).
activeboolWhether new orders may be placed. Open orders keep being checked either way.

Reverts:

setCosts

function setCosts(Costs calldata costs_) external onlyOwner

Replace 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)))
ParameterTypeDescription
costs_Costs calldataNew costs: scheduleGas, checkGas, fillGasHbarIn, fillGasTokenIn and gasPriceTinycents non-zero, and safetyBps at most 10,000.

Reverts:

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))
ParameterTypeDescription
impladdressThe IOrderType implementation. Non-zero.
ReturnsTypeDescription
iduint8The new type's id: the previous orderTypeCount. The uint8 counter allows 255 types (ids 0 to 254).

Reverts:

setOrderTypeActive

function setOrderTypeActive(uint8 id, bool active) external onlyOwner

Pause 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))
ParameterTypeDescription
iduint8A registered order-type id.
activeboolWhether new orders may use it.

Reverts:

fund

function fund() external payable

Endow 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 nonReentrant

Withdraw HBAR the vault holds beyond escrow, budgets, credits and the payer float.

  • Access: Owner only (onlyOwner)
  • Mutability: nonpayable
  • Selector: 0x65e73e32 (withdrawSurplus(address))
ParameterTypeDescription
toaddress payableRecipient of the surplus (OrderVaultLens.surplus previews the amount).

Reverts:

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.

ParameterTypeDescription
pPlaceParams calldataThe order; PlaceParams gives each field's bounds.
ReturnsTypeDescription
orderIduint256The new order's id, which is its NFT serial number.

Reverts:

cancel

function cancel(uint256 orderId) external nonReentrant

Cancel 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))
ParameterTypeDescription
orderIduint256An open order whose NFT the caller holds.

Reverts:

topUp

function topUp(uint256 orderId) external payable nonReentrant

Add 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.

ParameterTypeDescription
orderIduint256An open order.

Reverts:

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.

ParameterTypeDescription
orderIduint256An open order.
ReturnsTypeDescription
settledboolTrue 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:

claim

function claim(address token) external nonReentrant

Pull a payout that could not be delivered at settlement.

  • Access: Anyone, for their own credits.
  • Mutability: nonpayable
  • Selector: 0x1e83409a (claim(address))
ParameterTypeDescription
tokenaddressThe token to claim; address(0) for HBAR.

Reverts:

sweep

function sweep(uint256 marketId, uint32 epoch) external nonReentrant

Check 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).

ParameterTypeDescription
marketIduint256A listed market.
epochuint32The epoch a scheduled call was created under; manual calls may pass any value.

Reverts:

restartSweep

function restartSweep(uint256 marketId) external nonReentrant

Restart 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.

ParameterTypeDescription
marketIduint256A listed market with funded orders.

Reverts:

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.

ParameterTypeDescription
orderIduint256The order to fill.
oraclePriceuint256Chainlink cross price the floor is computed from (quote per 1 base, 8 decimals).
poolPriceuint256Pool TWAP price, reported in OrderFilled.
ReturnsTypeDescription
amountOutuint256Output paid to the holder (or credited for claim), in the output token's raw units.

Reverts:

  • OnlySelf for 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))
ParameterTypeDescription
marketIduint256A listed market (1 to marketCount).
ReturnsTypeDescription
–Market memoryThe market.

Reverts:

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))
ParameterTypeDescription
orderIduint256The order id (its NFT serial number).
ReturnsTypeDescription
–Order memoryThe 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))
ParameterTypeDescription
marketIduint256The market; an unlisted one returns an empty list.
ReturnsTypeDescription
–uint256[] memoryThe 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))
ParameterTypeDescription
orderIduint256The order id.
ReturnsTypeDescription
–addressThe 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))
ParameterTypeDescription
marketIduint256A listed market.
ReturnsTypeDescription
–GuardReading memoryThe reading; see GuardReading.

Reverts:

receive

receive() external payable

Receives HBAR the router unwraps when an order buys HBAR.

  • Access: The SaucerSwap router only.
  • Mutability: payable

Reverts:

  • NotRouter for any other sender; endow the vault through fund.

Events

CollectionCreated

event CollectionCreated(address collection)

initialize created the order NFT collection.

  • Topic 0: 0x75432e2e509efcaf947efcc7a5a6b6b3562425b29e9725c7a4a5c652291ac35d
FieldTypeIndexedDescription
collectionaddressnoThe 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
FieldTypeIndexedDescription
marketIduint256yesThe new market's id.
baseaddressnoBase token address.
quoteaddressnoQuote token address.
pooladdressnoThe SaucerSwap V2 pool it trades on.
poolFeeuint24noThe 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
FieldTypeIndexedDescription
marketIduint256yesThe market.

CostsUpdated

event CostsUpdated(Costs costs)

The costs were set, at deployment or by setCosts.

  • Topic 0: 0x5d1a796c088d803ba26be6a6756403de03c84173b28b892e34d7a46d9b2b7f88
FieldTypeIndexedDescription
costsCostsnoThe 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
FieldTypeIndexedDescription
orderIduint256yesThe order id (its NFT serial number).
marketIduint256yesThe market.
makeraddressyesThe caller, who received the order NFT.
sideSidenoSell the base, or buy it.
orderTypeuint8noThe order-type id.
amountInuint256noEscrowed input, in the input token's raw units.
typeParamuint256noThe type's parameter (trigger price or trail).
slippageBpsuint256noSlippage tolerance, in bps.
expiryuint256noExpiry time (unix seconds).
budgetuint256noCheck 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
FieldTypeIndexedDescription
iduint8yesThe type's id.
impladdressnoThe 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
FieldTypeIndexedDescription
iduint8yesThe type's id.
activeboolnoWhether 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.

FieldTypeIndexedDescription
orderIduint256yesThe order.
statebytes32noThe 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
FieldTypeIndexedDescription
orderIduint256yesThe 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
FieldTypeIndexedDescription
orderIduint256yesThe order.
holderaddressyesThe NFT holder, who received the output.
amountInuint256noInput swapped, in the input token's raw units.
amountOutuint256noOutput received, in the output token's raw units.
minAmountOutuint256noThe floor the swap had to meet.
oraclePriceuint256noChainlink cross price at the fill (quote per 1 base, 8 decimals).
poolPriceuint256noPool TWAP price at the fill, same units.
budgetRefunduint256noUnspent 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
FieldTypeIndexedDescription
orderIduint256yesThe order.
holderaddressyesThe NFT holder, who received the refunds.
refunduint256noEscrow returned, in the input token's raw units.
budgetRefunduint256noUnspent 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
FieldTypeIndexedDescription
orderIduint256yesThe order.
holderaddressyesThe NFT holder, who received the refunds.
refunduint256noEscrow returned, in the input token's raw units.
budgetRefunduint256noUnspent 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
FieldTypeIndexedDescription
orderIduint256yesThe order.
chargeduint256noTinybar taken from its budget.
budgetLeftuint256noBudget 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
FieldTypeIndexedDescription
orderIduint256yesThe order.
reasonGuardStatenoThe guard's verdict.
oraclePriceuint256noChainlink cross price (quote per 1 base, 8 decimals).
poolPriceuint256noPool 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
FieldTypeIndexedDescription
orderIduint256yesThe order.
reasonbytesnoThe 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
FieldTypeIndexedDescription
orderIduint256yesThe order.
budgetLeftuint256noBudget 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
FieldTypeIndexedDescription
orderIduint256yesThe order.
fromaddressyesWho paid.
amountuint256noTinybar added.
budgetuint256noThe 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
FieldTypeIndexedDescription
marketIduint256yesThe market.
scheduleaddressnoThe schedule's address.
executeAtuint256noWhen it is due (unix seconds).
epochuint256noThe 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
FieldTypeIndexedDescription
marketIduint256yesThe market.
epochuint256noThe 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
FieldTypeIndexedDescription
orderIduint256yesThe order.
chargeduint256noTinybar taken from its budget.
budgetLeftuint256noBudget 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
FieldTypeIndexedDescription
marketIduint256yesThe market.
responseCodeint64noThe 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
FieldTypeIndexedDescription
marketIduint256yesThe market.
scheduledboolnoTrue for a scheduled sweep, false for a manual call.
guardGuardStatenoThe guard's verdict during the sweep.
checkeduint256noOrders checked.
filleduint256noOrders filled.
openOrdersuint256noOpen 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
FieldTypeIndexedDescription
accountaddressyesThe recipient.
tokenaddressyesThe token; address(0) for HBAR.
amountuint256noAmount 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
FieldTypeIndexedDescription
accountaddressyesThe claimer.
tokenaddressyesThe token; address(0) for HBAR.
amountuint256noAmount 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
FieldTypeIndexedDescription
orderIduint256yesThe order.
responseCodeint64noThe HTS response code.

SurplusWithdrawn

event SurplusWithdrawn(address indexed to, uint256 amount)

The owner withdrew surplus HBAR.

  • Topic 0: 0xb94528ab6dc2c15743a47b933115b331b7beae78712677f1e345a9f1ae84bbd1
FieldTypeIndexedDescription
toaddressyesThe recipient.
amountuint256noTinybar sent.

Funded

event Funded(address indexed from, uint256 amount)

Someone endowed the vault through fund.

  • Topic 0: 0x5af8184bef8e4b45eb9f6ed7734d04da38ced226495548f46e0c8ff8d7d9a524
FieldTypeIndexedDescription
fromaddressyesWho paid.
amountuint256noTinybar 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
ParameterTypeDescription
marketIduint256The id asked for.

MarketInactive

error MarketInactive(uint256 marketId)

The market is paused for new orders.

  • Selector: 0x427a54ec
ParameterTypeDescription
marketIduint256The 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
ParameterTypeDescription
iduint8The id asked for.

OrderTypeInactive

error OrderTypeInactive(uint8 id)

The order type is disabled for new orders.

  • Selector: 0x33970f22
ParameterTypeDescription
iduint8The 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
ParameterTypeDescription
slippageBpsuint256The slippage given, in bps.
minBpsuint256The smallest accepted: the pool fee in bps (poolFee / 100) plus 1.
maxBpsuint256The 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
ParameterTypeDescription
expiryuint256The expiry given.

InsufficientBudget

error InsufficientBudget(uint256 provided, uint256 required)

The check budget is below the minimum (OrderVaultLens.minBudget).

  • Selector: 0xa9a711d0
ParameterTypeDescription
provideduint256The budget sent, in tinybar.
requireduint256The minimum, in tinybar.

WrongValue

error WrongValue(uint256 sent, uint256 expected)

An HBAR-input order sent less value than its amountIn.

  • Selector: 0x195a3ca1
ParameterTypeDescription
sentuint256msg.value, in tinybar.
expecteduint256The order's amountIn.

OrderNotOpen

error OrderNotOpen(uint256 orderId)

The order is not open (unknown, filled, cancelled or expired).

  • Selector: 0x410e0437
ParameterTypeDescription
orderIduint256The order.

NotHolder

error NotHolder(uint256 orderId, address caller)

The caller does not hold the order's NFT.

  • Selector: 0x2f5ea621
ParameterTypeDescription
orderIduint256The order.
calleraddressThe 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
ParameterTypeDescription
marketIduint256The market.
nextSweepAtuint256When the pending sweep is due (unix seconds).

NoFundedOrders

error NoFundedOrders(uint256 marketId)

restartSweep was called for a market with no funded orders.

  • Selector: 0x30a2f79b
ParameterTypeDescription
marketIduint256The market.

NotRouter

error NotRouter(address sender)

HBAR arrived through receive from someone other than the router; use fund instead.

  • Selector: 0x2462ed09
ParameterTypeDescription
senderaddressThe 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.

ReturnsTypeDescription
–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.

ReturnsTypeDescription
–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:

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.

ParameterTypeDescription
newOwneraddress–

Reverts:

OwnershipTransferStarted

event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner)
  • Inherited from Ownable2Step
  • Topic 0: 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700
FieldTypeIndexedDescription
previousOwneraddressyes–
newOwneraddressyes–

OwnershipTransferred

event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)
  • Inherited from Ownable
  • Topic 0: 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0
FieldTypeIndexedDescription
previousOwneraddressyes–
newOwneraddressyes–

OwnableInvalidOwner

error OwnableInvalidOwner(address owner)
  • Declared in Ownable
  • Selector: 0x1e4fbdf7

The owner is not a valid owner account. (eg. address(0))

ParameterTypeDescription
owneraddress–

OwnableUnauthorizedAccount

error OwnableUnauthorizedAccount(address account)
  • Declared in Ownable
  • Selector: 0x118cdaa7

The caller account is not authorized to perform an operation.

ParameterTypeDescription
accountaddress–

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.

ParameterTypeDescription
bitsuint8–
valueuint256–

Other errors in this ABI: HtsError.

OrderVaultLens

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

NameDeclarationDescription
VAULTOrderVault public immutable VAULTThe vault this lens reads.

Functions

constructor

constructor(OrderVault vault_)
  • Mutability: nonpayable
ParameterTypeDescription
vault_OrderVaultThe 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))
ParameterTypeDescription
marketIduint256A listed market.
ReturnsTypeDescription
–uint256Tinybar per check.

Reverts:

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))
ParameterTypeDescription
fundedOrdersuint256Orders sharing the sweep's fixed cost; 0 is treated as 1.
ReturnsTypeDescription
–uint256Tinybar 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))
ParameterTypeDescription
marketIduint256A listed market.
sideSideThe order's side, which decides whether its input is HBAR.
ReturnsTypeDescription
–uint256The reserve, in tinybar.

Reverts:

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))
ParameterTypeDescription
marketIduint256A listed market.
sideSideThe order's side, which decides whether its input is HBAR.
ReturnsTypeDescription
–uint256The minimum budget, in tinybar.

Reverts:

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))
ParameterTypeDescription
marketIduint256A listed market.
ReturnsTypeDescription
–uint256The gas limit.

Reverts:

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())
ReturnsTypeDescription
floatuint256The 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())
ReturnsTypeDescription
–uint256The 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))
ParameterTypeDescription
marketIduint256A listed market.
ReturnsTypeDescription
shareuint256Tinybar charged to each order that can pay.
parkFeeuint256Tinybar charged to each order that is parked.

Reverts:

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))
ParameterTypeDescription
marketIduint256A listed market.
ReturnsTypeDescription
batchuint256[] memoryThe order ids, in visiting order.

Reverts:

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.

ParameterTypeDescription
marketIduint256A listed market.
orderTypeuint8The order-type id.
sideSideThe order's side.
typeParamuint128The type's parameter (trigger price or trail), as in PlaceParams.
expiryuint256The order's expiry (unix seconds); the delay never runs past it.
ReturnsTypeDescription
–uint256Seconds until the check, within the market's minInterval and maxInterval.

Reverts:

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))
ParameterTypeDescription
orderIduint256The order.
ReturnsTypeDescription
–uint256Seconds 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))
ParameterTypeDescription
marketIduint256A listed market.
ReturnsTypeDescription
statusSweepStatusIdle, Scheduled or Stalled.
nextSweepAtuint256When the pending (or missed) sweep is due (unix seconds); 0 when Idle.

Reverts:

Errors

InvalidCosts

error InvalidCosts()

The exchange-rate system contract did not answer; the same error the vault raises for it.

  • Selector: 0x1b44ea81

LimitOrderType

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))
ParameterTypeDescription
(unnamed)SideUnused by this type.
amountInuint128Amount escrowed; greater than 0.
paramuint128Trigger price, quote per 1 base with 8 decimals; greater than 0.
(unnamed)uint16Unused by this type.
(unnamed)uint40Unused by this type.
(unnamed)uint40Unused by this type.
ReturnsTypeDescription
–boolWhether 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))
ParameterTypeDescription
sideSideSell or buy.
paramuint128Trigger price (quote per 1 base, 8 decimals).
statebytes32Returned unchanged: the type is stateless.
oraclePriceuint256The Chainlink cross price for the market.
ReturnsTypeDescription
distanceBpsuint2560 when the trigger is met; otherwise the gap in bps of the price, at least 1.
newStatebytes32state, 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))
ParameterTypeDescription
(unnamed)SideUnused by this type.
(unnamed)uint128Unused by this type.
(unnamed)uint128Unused by this type.
(unnamed)uint256Unused by this type.
ReturnsTypeDescription
–uint256Always 0.

StopOrderType

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))
ParameterTypeDescription
(unnamed)SideUnused by this type.
amountInuint128Amount escrowed; greater than 0.
paramuint128Trigger price, quote per 1 base with 8 decimals; greater than 0.
(unnamed)uint16Unused by this type.
(unnamed)uint40Unused by this type.
(unnamed)uint40Unused by this type.
ReturnsTypeDescription
–boolWhether 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))
ParameterTypeDescription
sideSideSell or buy.
paramuint128Trigger price (quote per 1 base, 8 decimals).
statebytes32Returned unchanged: the type is stateless.
oraclePriceuint256The Chainlink cross price for the market.
ReturnsTypeDescription
distanceBpsuint2560 when the trigger is met; otherwise the gap in bps of the price, at least 1.
newStatebytes32state, 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))
ParameterTypeDescription
(unnamed)SideUnused by this type.
(unnamed)uint128Unused by this type.
(unnamed)uint128Unused by this type.
(unnamed)uint256Unused by this type.
ReturnsTypeDescription
–uint256Always 0.

TrailingStopType

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

NameDeclarationDescription
MIN_TRAIL_BPSuint128 public constant MIN_TRAIL_BPS = 50Smallest trail accepted, in bps (0.5%).
MAX_TRAIL_BPSuint128 public constant MAX_TRAIL_BPS = 5000Largest 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].

ParameterTypeDescription
sideSideMust be SellBase.
amountInuint128Amount escrowed; greater than 0.
paramuint128The trail, in bps: MIN_TRAIL_BPS (50) to MAX_TRAIL_BPS (5,000).
(unnamed)uint16Unused by this type.
(unnamed)uint40Unused by this type.
(unnamed)uint40Unused by this type.
ReturnsTypeDescription
–boolWhether 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))
ParameterTypeDescription
(unnamed)SideUnused by this type.
paramuint128The trail, in bps.
statebytes32The peak price so far, as bytes32; zero before the first check.
oraclePriceuint256The Chainlink cross price for the market.
ReturnsTypeDescription
distanceBpsuint2560 when the trigger is met; otherwise the gap in bps of the price, at least 1.
newStatebytes32The 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))
ParameterTypeDescription
(unnamed)SideUnused by this type.
(unnamed)uint128Unused by this type.
(unnamed)uint128Unused by this type.
(unnamed)uint256Unused by this type.
ReturnsTypeDescription
–uint256Always 0.

IOrderType

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))
ParameterTypeDescription
sideSideSell the base, or buy it.
amountInuint128Amount escrowed.
paramuint128The type's parameter: a trigger price for limit/stop, a trail in bps for trailing.
slippageBpsuint16Maker's slippage tolerance.
expiryuint40Order expiry (unix seconds).
nowTsuint40Current block timestamp, passed in so the strategy stays pure.
ReturnsTypeDescription
okboolWhether 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))
ParameterTypeDescription
sideSideSell or buy.
paramuint128The type parameter (see validate).
statebytes32This order's opaque per-type state (e.g. a trailing peak); zero for a new order.
oraclePriceuint256The Chainlink cross price for the market, in the market's price units.
ReturnsTypeDescription
distanceBpsuint2560 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.
newStatebytes32The 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))
ParameterTypeDescription
sideSideSell or buy.
amountInuint128Amount escrowed.
paramuint128The type parameter (see validate).
oraclePriceuint256The Chainlink cross price for the market.
ReturnsTypeDescription
–uint256The 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

NameDeclarationDescription
MIN_TWAP_WINDOWuint256 internal constant MIN_TWAP_WINDOW = 300Shortest twapWindow: a shorter window is close to spot price.
MAX_TWAP_WINDOWuint256 internal constant MAX_TWAP_WINDOW = 1 daysLongest twapWindow: a longer one outruns SaucerSwap's observation history.
MIN_ORACLE_AGEuint256 internal constant MIN_ORACLE_AGE = 60Shortest maxOracleAge.
MAX_ORACLE_AGEuint256 internal constant MAX_ORACLE_AGE = 26 hoursLongest maxOracleAge: Hedera's Chainlink feeds have a 24 h heartbeat; allow two hours of slack on top.
MAX_DEVIATION_BPSuint256 internal constant MAX_DEVIATION_BPS = 1_000Largest maxDeviationBps (10%).
MAX_SLIPPAGE_BPSuint256 internal constant MAX_SLIPPAGE_BPS = 1_000Largest 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
ParameterTypeDescription
gGuardParams calldataThe 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.
poolFeeuint24The market pool's fee, in hundredths of a basis point.
ReturnsTypeDescription
–boolWhether 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.

ParameterTypeDescription
mMarket storageThe market, in the vault's storage.
ReturnsTypeDescription
rGuardReading memoryThe 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.

ParameterTypeDescription
feedIAggregatorV3A Chainlink aggregator.
ReturnsTypeDescription
answeruint256The answer, in the feed's decimals; 0 when unusable.
updatedAtuint256The 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.

ParameterTypeDescription
valueint256–

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

NameDeclarationDescription
HTSIHederaTokenService internal constant HTS = IHederaTokenService(address(0x167))The HTS system contract.
MIN_SWEEP_INTERVALuint256 internal constant MIN_SWEEP_INTERVAL = 30Shortest minInterval. HIP-1215 caps expiry 62 days ahead; the minimum is a few seconds past consensus time.
MAX_SWEEP_INTERVALuint256 internal constant MAX_SWEEP_INTERVAL = 1 daysLongest maxInterval.

Functions

list

function list(Market storage m, Market calldata market) external

Validate 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
ParameterTypeDescription
mMarket storageThe vault's empty storage slot for the new market.
marketMarket calldataThe market to list; Market gives each field's bounds.

Reverts:

update

function update(Market storage m, GuardParams calldata guard, SweepParams calldata sweep, bool active) external

Retune 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
ParameterTypeDescription
mMarket storageThe listed market, in the vault's storage.
guardGuardParams calldataNew guard settings, checked against the market's stored poolFee.
sweepSweepParams calldataNew sweep settings.
activeboolWhether new orders may be placed.

Reverts:

_validate

function _validate(GuardParams calldata g, SweepParams calldata p, uint24 poolFee) private pure

The 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
ParameterTypeDescription
gGuardParams calldataGuard settings.
pSweepParams calldataSweep settings.
poolFeeuint24The market pool's fee, in hundredths of a basis point.

Reverts:

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

NameDeclarationDescription
HTSIHederaTokenService internal constant HTS = IHederaTokenService(address(0x167))The HTS system contract.
HTS_SUCCESSint64 internal constant HTS_SUCCESS = 22HTS response code for success.
KEYS_SUPPLY_AND_WIPEuint256 internal constant KEYS_SUPPLY_AND_WIPE = 16 | 8HTS key-type bits for the supply (16) and wipe (8) keys.
AUTO_RENEW_PERIODint64 internal constant AUTO_RENEW_PERIOD = 7_776_000The 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
ParameterTypeDescription
namestring calldataCollection name.
symbolstring calldataCollection symbol.
feeuint256HBAR (tinybar) forwarded as the HTS creation fee; any excess stays in the vault.
ReturnsTypeDescription
rcint64The HTS response code.
collectionaddressThe 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

NameDeclarationDescription
HTS_SUCCESSint64 internal constant HTS_SUCCESS = 22HTS response code for success.
HTS_ALREADY_ASSOCIATEDint64 internal constant HTS_ALREADY_ASSOCIATED = 194HTS response code for a token already associated with the account.
HBARaddress internal constant HBAR = address(0)Stands for HBAR in token arguments.
SWAP_DEADLINEuint256 internal constant SWAP_DEADLINE = 300Seconds 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
ParameterTypeDescription
routerISaucerSwapV2RouterThe SaucerSwap V2 SwapRouter.
whbaraddressThe WHBAR token, substituted for an HBAR leg.
poolFeeuint24The pool's fee, in hundredths of a basis point.
tokenInaddressInput token; address(0) for HBAR.
tokenOutaddressOutput token; address(0) for HBAR.
amountInuint256Input amount, in raw units.
minOutuint256Smallest acceptable output, in raw units.
ReturnsTypeDescription
amountOutuint256Output received, in raw units.

Reverts:

  • TransferRejected if approving the router for a token input returns false. The router reverts if the output is below minOut.

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
ParameterTypeDescription
htsIHederaTokenServiceThe HTS system contract.
collectionaddressThe order NFT collection.
toaddressThe maker.
ReturnsTypeDescription
orderIduint256The minted serial number.

Reverts:

  • HtsError (Mint or TransferNft) 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
ParameterTypeDescription
htsIHederaTokenServiceThe HTS system contract.
collectionaddressThe order NFT collection.
orderIduint256The order's serial number.
holderaddressThe NFT's current holder.
ReturnsTypeDescription
rcint64The HTS response code (22 is success).

associate

function associate(IHederaTokenService hts, address token) public

Associate the vault with an HTS token (idempotent).

  • Mutability: nonpayable
  • Visibility: public
  • Used by: MarketRegistry.list
ParameterTypeDescription
htsIHederaTokenServiceThe HTS system contract.
tokenaddressThe 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
ParameterTypeDescription
tokenaddressThe token.
fromaddressThe owner, who must have approved the vault.
toaddressThe recipient (the vault).
amountuint256Amount, in raw units.
ReturnsTypeDescription
–boolWhether 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
ParameterTypeDescription
tokenaddressThe token.
toaddressThe recipient.
amountuint256Amount, in raw units.
ReturnsTypeDescription
–boolWhether 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

NameDeclarationDescription
RATE_UNITuint256 internal constant RATE_UNIT = 1e12Tinycents converted per exchange-rate lookup.
MIN_CHECKS_FUNDEDuint256 internal constant MIN_CHECKS_FUNDED = 6Solo checks a new order must be able to pay for on top of its reserve.
SWEEP_GRACEuint256 internal constant SWEEP_GRACE = 120A 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
ParameterTypeDescription
cCosts memoryThe vault's costs.
gasuint256Gas units.
rateuint256Tinybar per RATE_UNIT tinycents, from the 0x168 exchange-rate system contract.
ReturnsTypeDescription
–uint256Tinybar.

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
ParameterTypeDescription
cCosts memoryThe vault's costs.
fundedOrdersuint256Orders sharing the fixed cost; at least 1 (pass 1 for a solo check).
rateuint256Tinybar per RATE_UNIT tinycents, from the 0x168 exchange-rate system contract.
ReturnsTypeDescription
–uint256Tinybar 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
ParameterTypeDescription
cCosts memoryThe vault's costs.
hbarInboolWhether the order's input is HBAR.
ReturnsTypeDescription
–uint256Gas 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
ParameterTypeDescription
cCosts memoryThe vault's costs.
ReturnsTypeDescription
–uint256Gas 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
ParameterTypeDescription
cCosts memoryThe vault's costs.
ReturnsTypeDescription
–uint256Gas 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
ParameterTypeDescription
cCosts memoryThe vault's costs.
hbarInboolWhether the order's input is HBAR.
rateuint256Tinybar per RATE_UNIT tinycents, from the 0x168 exchange-rate system contract.
ReturnsTypeDescription
–uint256Tinybar.

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
ParameterTypeDescription
cCosts memoryThe vault's costs.
hbarInboolWhether the order's input is HBAR.
rateuint256Tinybar per RATE_UNIT tinycents, from the 0x168 exchange-rate system contract.
ReturnsTypeDescription
–uint256Tinybar.

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
ParameterTypeDescription
cCosts memoryThe vault's costs.
spSweepParams memoryThe market's sweep settings.
openOrdersuint256The market's open orders.
ReturnsTypeDescription
–uint256Gas 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
ParameterTypeDescription
spSweepParams memoryThe market's sweep settings.
distanceBpsuint256The order's distance from its trigger, in bps.
expiryuint256The order's expiry (unix seconds).
nowTsuint256The current block timestamp.
ReturnsTypeDescription
duint256Seconds: 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
ParameterTypeDescription
pendingScheduleaddressThe pending schedule's address; zero when none.
nextSweepAtuint256When the pending sweep is due (unix seconds).
nowTsuint256The current block timestamp.
ReturnsTypeDescription
–boolTrue 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
ParameterTypeDescription
cCosts memoryThe vault's costs.
rateuint256Tinybar per RATE_UNIT tinycents, from the 0x168 exchange-rate system contract.
ordersChargeInput[] memoryThe batch's orders.
ReturnsTypeDescription
shareuint256Tinybar charged to each order that can pay.
parkFeeuint256Tinybar 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.

FieldTypeDescription
liveboolOpen, funded and not expired.
budgetuint256The order's budget, in tinybar.
reserveuint256reserve() 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

NameDeclarationDescription
PRICE_SCALEuint256 internal constant PRICE_SCALE = 1e8Prices carry 8 decimals.
BPSuint256 internal constant BPS = 10_000Basis points in 1.
RAYuint256 internal constant RAY = 1e2727-decimal fixed point for the tick math.
TICK_BASE_RAYuint256 internal constant TICK_BASE_RAY = 1_000_100_000_000_000_000_000_000_0001.0001 in RAY: the price ratio between adjacent Uniswap-v3 style ticks.
MAX_TICKint24 internal constant MAX_TICK = 887_272Uniswap 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
ParameterTypeDescription
exponentuint256The power, at most MAX_TICK in practice.
ReturnsTypeDescription
resultuint2561.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
ParameterTypeDescription
cumulativeStartint56The tick cumulative at the start of the window.
cumulativeEndint56The tick cumulative at the end of the window.
windowuint32The window, in seconds; non-zero.
ReturnsTypeDescription
–int24The 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.

ParameterTypeDescription
tickint24A pool tick, within plus or minus MAX_TICK (887,272).
baseIsToken0boolWhether the base is the pool's token0.
baseDecimalsuint8The base token's decimals.
quoteDecimalsuint8The quote token's decimals.
ReturnsTypeDescription
–uint256Quote per 1 base, 8 decimals.

Reverts:

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
ParameterTypeDescription
baseUsduint256The base/USD answer.
baseFeedDecimalsuint8The base feed's decimals.
quoteUsduint256The quote/USD answer; non-zero.
quoteFeedDecimalsuint8The quote feed's decimals.
ReturnsTypeDescription
–uint256Quote 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
ParameterTypeDescription
baseAmountuint256Base amount, in raw units.
priceuint256Quote per 1 base, 8 decimals.
baseDecimalsuint8The base token's decimals.
quoteDecimalsuint8The quote token's decimals.
ReturnsTypeDescription
–uint256Quote 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
ParameterTypeDescription
quoteAmountuint256Quote amount, in raw units.
priceuint256Quote per 1 base, 8 decimals; non-zero.
baseDecimalsuint8The base token's decimals.
quoteDecimalsuint8The quote token's decimals.
ReturnsTypeDescription
–uint256Base 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
ParameterTypeDescription
auint256The value compared.
buint256The reference; non-zero.
ReturnsTypeDescription
–uint256The 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
ParameterTypeDescription
triggeruint256The trigger price.
priceuint256The current price; non-zero.
ReturnsTypeDescription
–uint256The 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
ParameterTypeDescription
amountuint256The amount.
bpsuint256Basis points to take off, at most 10,000.
ReturnsTypeDescription
–uint256The reduced amount.

Errors

TickOutOfRange

error TickOutOfRange(int24 tick)

A tick outside the Uniswap v3 range of plus or minus 887,272.

  • Selector: 0xdd455374
ParameterTypeDescription
tickint24The 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.

ValueNameDescription
0SellBaseSell amountIn of the base token for the quote token.
1BuyBaseSpend 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.

ValueNameDescription
0AtOrAboveFires when the price is at or above the trigger.
1AtOrBelowFires when the price is at or below the trigger.

Status

enum Status {
    None,
    Open,
    Filled,
    Cancelled,
    Expired
}

An order's lifecycle state.

ValueNameDescription
0NoneNo order with this id.
1OpenEscrowed and waiting for its trigger.
2FilledSwapped; the output was paid to the NFT holder (or credited for claim).
3CancelledCancelled by its holder; escrow and unused budget refunded.
4ExpiredReached its expiry unfilled; escrow and unused budget refunded.

HtsOperation

enum HtsOperation {
    CreateCollection,
    Mint,
    TransferNft,
    Associate
}

Which HTS operation failed, for the shared HtsError.

ValueNameDescription
0CreateCollectionCreating the order NFT collection in initialize.
1MintMinting an order NFT in placeOrder.
2TransferNftMoving a newly minted order NFT from the vault to the maker.
3AssociateAssociating 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.

ValueNameDescription
0OpenBoth feeds are valid and fresh and the pool TWAP is within maxDeviationBps of Chainlink.
1OracleInvalidA feed reverted, answered zero or less, or reported a zero or future update time.
2OracleStaleThe older feed update is more than maxOracleAge seconds old.
3TwapUnavailableThe pool could not report a TWAP over twapWindow (too little observation history).
4DeviationTooHighThe 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.

FieldTypeDescription
baseaddressBase token address (an HTS token; the WHBAR token when baseIsHbar). Non-zero, distinct from quote.
quoteaddressQuote token address (an HTS token; the WHBAR token when quoteIsHbar). Non-zero.
baseDecimalsuint8The base token's decimals (8 for HBAR).
quoteDecimalsuint8The quote token's decimals.
baseIsHbarboolThe base leg is native HBAR: escrow and payouts in HBAR, routed through WHBAR.
quoteIsHbarboolThe quote leg is native HBAR. At most one of the two legs may be HBAR.
baseFeedIAggregatorV3Chainlink base/USD feed. Non-zero.
quoteFeedIAggregatorV3Chainlink quote/USD feed. Non-zero.
baseFeedDecimalsuint8Read from baseFeed.decimals() by listMarket; the value passed in is ignored.
quoteFeedDecimalsuint8Read from quoteFeed.decimals() by listMarket; the value passed in is ignored.
poolISaucerSwapV2PoolSaucerSwap V2 pool for the pair, used for the TWAP and the swap. Non-zero.
poolFeeuint24The 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.
baseIsToken0boolSet by listMarket from pool.token0(); the value passed in is ignored.
activeboolWhether new orders may be placed. listMarket sets it to true (the value passed in is ignored); updateMarket changes it.
guardGuardParamsThe guard's bounds; see GuardParams.
sweepSweepParamsThe 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.

FieldTypeDescription
twapWindowuint32Seconds of pool TWAP compared with Chainlink: 300 to 86,400 (5 minutes to 1 day).
maxDeviationBpsuint16Largest TWAP-to-Chainlink gap, in bps, at which a fill may proceed: 1 to 1,000.
maxOracleAgeuint32Oldest acceptable feed update, in seconds: 60 to 93,600 (26 hours).
maxSlippageBpsuint16Largest 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].

FieldTypeDescription
minIntervaluint32Shortest wait between sweeps, in seconds: at least 30 and at most maxInterval.
maxIntervaluint32Longest wait between sweeps, in seconds: at most 86,400 (1 day).
maxMoveBpsPerHouruint16The price move per hour, in bps, the schedule assumes. Greater than 0.
maxOrdersuint16Open orders one sweep visits, from a rotating cursor. Greater than 0.
maxFillsuint8Fills 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)).

FieldTypeDescription
pendingScheduleaddressThe HSS schedule of the next sweep; zero when none is pending.
nextSweepAtuint40When the pending sweep is due (unix seconds).
cursoruint32Index in the market's open-order list where the next batch starts.
fundedOrdersuint32Open orders whose budget still pays for checks; the chain keeps running while it is above 0.
epochuint32Bumped on every new schedule; a scheduled sweep carrying an older epoch has been superseded.
heldStreakuint8Consecutive 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.

ValueNameDescription
0IdleNo funded orders, so no sweep is needed.
1ScheduledA sweep is pending and not overdue.
2StalledFunded 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.

FieldTypeDescription
scheduleGasuint32The HSS scheduling fee, as gas. Non-zero.
sweepBaseGasuint32A sweep's fixed gas besides scheduling and its orders.
checkGasuint32Gas to check one order. Non-zero.
fillGasHbarInuint32Gas to fill an order whose input is HBAR, before settlement. Non-zero.
fillGasTokenInuint32Gas to fill an order whose input is an HTS token, before settlement. Non-zero.
settleGasuint32Gas to settle one order (payouts and retiring its NFT); added to every fill and expiry.
idleSweepGasuint32A sweep that finds nothing to do: superseded by an earlier one, or left with no funded orders.
gasPriceTinycentsuint32Hedera prices gas in USD; converted to tinybar through the 0x168 exchange-rate contract. Non-zero.
safetyBpsuint16Margin 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.

FieldTypeDescription
marketIduint32The market it trades on.
sideSideSell the base, or buy it.
orderTypeuint8Index into the vault's order-type registry (limit, stop, trailing, …).
statusStatusLifecycle state.
fundedboolWhether its budget still pays for scheduled checks. A parked order is not checked until topUp.
slippageBpsuint16The maker's slippage tolerance, in bps.
createdAtuint40Placement time (unix seconds).
expiryuint40Expiry time (unix seconds); the order is refunded at the first check at or after it.
amountInuint128Escrowed input amount, in the input token's raw units (tinybar for HBAR).
typeParamuint128The type's parameter: a trigger price for limit/stop, a trail in bps for trailing.
budgetuint128Unspent HBAR (tinybar) prepaid for checks and the fill.
typeStatebytes32The 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.

FieldTypeDescription
marketIduint32A listed, active market.
sideSideSell the base, or buy it. The input token is the base for SellBase and the quote for BuyBase.
orderTypeuint8A registered, active order-type id. The deploy script registers limit as 0, stop as 1 and trailing stop as 2.
amountInuint128Amount to escrow, in the input token's raw units (tinybar for HBAR). Greater than 0.
typeParamuint128For 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.
slippageBpsuint16Slippage tolerance, in bps: above the market's poolFee / 100 and at most its guard.maxSlippageBps.
expiryuint40Expiry 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).

FieldTypeDescription
stateGuardStateThe verdict; only Open lets an order fill.
oraclePriceuint256Chainlink cross price, quote per 1 base with 8 decimals; 0 when the state is OracleInvalid.
poolPriceuint256Pool TWAP price in the same units; 0 unless the TWAP was read.
deviationBpsuint256Gap between poolPrice and oraclePrice, in bps of oraclePrice; 0 unless computed.
oracleUpdatedAtuint256The 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
ParameterTypeDescription
operationHtsOperationThe HTS operation that failed.
responseCodeint64The HTS response code it returned (22 is success).

From docs/CONTRACT-API.md at v1.1 (cee2d4e) · View source

On this page