// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; /** * @title SOMA Escrow Contract. * @author SOMA.finance * @notice An off-chain-settled brokerage escrow. Users escrow a stablecoin to buy tokenized equities * (e.g. sTSLA), or escrow share tokens to sell them; an authorized operator (backend API) settles the * order on-chain after executing the corresponding trade off-chain. Orders fill incrementally: an * operator may settle an order over many fills and it completes when the owner's target output is * reached or their input is exhausted, refunding whatever is left. Slippage is bounded on-chain by a * minimum-amount-out floor that every individual fill must clear; limit/stop intent is recorded * as metadata and enforced off-chain. */ interface ISomaEscrow { /** * @notice The direction of an order. * @param BUY Stablecoin in, share tokens out. * @param SELL Share tokens in, stablecoin out. */ enum Side { BUY, SELL } /** * @notice The order type. On-chain all types collapse to "cumulative output >= the pro-rata share of * minAmountOut earned by the input consumed, before the applicable deadline"; the type and * {Order-triggerPrice} are recorded for off-chain (API) logic. * @param MARKET Fill at the prevailing price (bounded by minAmountOut). * @param LIMIT Fill only at or better than the limit price encoded by minAmountOut. * @param STOP Trigger at triggerPrice then fill as market (bounded by minAmountOut). */ enum OrderType { MARKET, LIMIT, STOP } /** * @notice The lifecycle status of an order. */ enum OrderStatus { NONE, OPEN, LOCKED, FILLED, CANCELLED, EXPIRED } /** * @notice Per share-token market configuration. * @param enabled Whether the market is open for placing orders. * @param partitionId The {SecurityToken} partition that backs the ERC20 balance (usually DEFAULT_PARTITION). * @param requiredPrivileges The guard privileges an account must hold to trade this market. */ struct Market { bool enabled; bytes32 partitionId; bytes32 requiredPrivileges; } /** * @notice An escrow order. * @param owner The account that placed the order and receives fills/refunds. * @param side The order direction. * @param orderType The order type (metadata for the off-chain operator). * @param status The current lifecycle status. * @param shareToken The {SecurityToken} being bought or sold. * @param expiry The single deadline the owner set. The order can be filled only before it and reclaimed * only at or after it, whether the order is OPEN or LOCKED. This is the owner's guaranteed withdrawal time. * @param lockedUntil While LOCKED, the timestamp at which the lock goes stale and the owner may cancel * again. Set to `now + minSettlementWindow` by {lockOrder}; cleared on unlock and on any fill that * leaves the order live. Zero when the order is not locked. * @param amountIn BUY: stablecoin escrowed. SELL: share tokens escrowed. * @param minAmountOut BUY: minimum shares out. SELL: minimum stablecoin out. The slippage floor for * consuming the *whole* of amountIn, which makes it a rate cap of `amountIn / minAmountOut`. EVERY fill * must independently clear that rate — the floor is enforced per increment, not merely on the running * totals — so no fill can ever be priced below it. * @param targetAmountOut The output quantity the owner actually wants, and a hard ceiling: no fill may * push {filledOut} above it. Once {filledOut} reaches it the order completes and any unconsumed * {amountIn} is refunded. Zero means "no target" — the order runs until amountIn is exhausted, with no * size ceiling at all (the natural choice for MARKET orders). This is deliberately NOT constrained * against minAmountOut: whenever amountIn carries a buffer above the target's expected cost, the rate * cap the owner wants implies a minAmountOut *above* targetAmountOut. * @param filledIn Cumulative input consumed so far. The unfilled remainder is `amountIn - filledIn`. * @param filledOut Cumulative output delivered to the owner so far. * @param triggerPrice The limit/stop reference price (metadata only; stablecoin-per-share, scaled 1e18). * @param partitionId Snapshot of the market's partition at placement. * @param requiredPrivileges Snapshot of the market's required privileges at placement. */ struct Order { address owner; Side side; OrderType orderType; OrderStatus status; address shareToken; uint48 expiry; uint48 lockedUntil; uint256 amountIn; uint256 minAmountOut; uint256 targetAmountOut; uint256 filledIn; uint256 filledOut; uint256 triggerPrice; bytes32 partitionId; bytes32 requiredPrivileges; } /** * @notice Emitted when an order is placed. * @param orderId The id of the created order. * @param owner The account that placed the order. * @param shareToken The share token being bought or sold. * @param side The order direction. * @param orderType The order type. * @param amountIn BUY: stablecoin escrowed. SELL: share tokens escrowed. * @param minAmountOut The on-chain slippage floor for the whole order. * @param targetAmountOut The output quantity that completes the order (0 = no target). * @param triggerPrice The limit/stop reference price (metadata). * @param expiry The owner's guaranteed withdrawal deadline. */ event OrderPlaced( uint256 indexed orderId, address indexed owner, address indexed shareToken, Side side, OrderType orderType, uint256 amountIn, uint256 minAmountOut, uint256 targetAmountOut, uint256 triggerPrice, uint48 expiry ); /** * @notice Emitted when an operator locks an order ahead of an off-chain trade. * @param orderId The id of the locked order. * @param lockedUntil The timestamp after which the lock is stale and the owner may cancel again. * @param operator The operator that locked the order. */ event OrderLocked(uint256 indexed orderId, uint48 lockedUntil, address indexed operator); /** * @notice Emitted when a refund could not be delivered and was booked as a claimable balance instead — * for example a seller whose guard privileges lapsed, or a buyer blocklisted by the stablecoin. The * order still reached its terminal state; the owner collects with {claim} once unblocked. * @param orderId The order whose refund was deferred. * @param owner The account the refund is owed to. * @param token The token owed. * @param amount The amount owed. */ event RefundDeferred(uint256 indexed orderId, address indexed owner, address indexed token, uint256 amount); /** * @notice Emitted when a previously deferred refund is collected. * @param owner The account that collected. * @param token The token collected. * @param amount The amount collected. */ event RefundClaimed(address indexed owner, address indexed token, uint256 amount); /** * @notice Emitted when an operator unlocks a previously locked order. * @param orderId The id of the unlocked order. * @param operator The operator that unlocked the order. */ event OrderUnlocked(uint256 indexed orderId, address indexed operator); /** * @notice Emitted for each fill against an order. An order may be filled many times; the order is only * finished when {OrderCompleted} is emitted. * @param orderId The id of the filled order. * @param owner The order owner that received the fill. * @param shareToken The share token bought or sold. * @param side The order direction. * @param amountIn Consumed by *this* fill. BUY: stablecoin spent. SELL: shares sold. * @param amountOut Delivered by *this* fill. BUY: shares. SELL: stablecoin. * @param feeAmount The commission collected by the desk on this fill, as reported by the operator * (stablecoin units). Recorded for off-chain accounting/receipts only: the contract neither computes * nor enforces it, and it moves no funds — on a BUY it is already included in `amountIn`, on a SELL * it has already been deducted from `amountOut`. * @param effectivePrice The realized price of this fill (stablecoin-per-share, scaled 1e18). * @param filledIn Cumulative input consumed across all fills, including this one. * @param filledOut Cumulative output delivered across all fills, including this one. * @param operator The operator that settled the fill. */ event OrderFilled( uint256 indexed orderId, address indexed owner, address indexed shareToken, Side side, uint256 amountIn, uint256 amountOut, uint256 feeAmount, uint256 effectivePrice, uint256 filledIn, uint256 filledOut, address operator ); /** * @notice Emitted when an order reaches its terminal FILLED state — because its target was reached, its * input was exhausted, or an operator closed it. Any unconsumed input has been refunded by this point. * @param orderId The id of the completed order. * @param owner The order owner. * @param filledIn Total input consumed over the order's life. * @param filledOut Total output delivered over the order's life. * @param refundAmount The unconsumed input returned to the owner (0 if the input was exhausted). * @param sender The account that triggered completion. */ event OrderCompleted( uint256 indexed orderId, address indexed owner, uint256 filledIn, uint256 filledOut, uint256 refundAmount, address sender ); /** * @notice Emitted when an order is cancelled (by the owner or by an admin). * @param orderId The id of the cancelled order. * @param owner The order owner that was refunded. * @param refundAmount The amount refunded to the owner. * @param sender The account that triggered the cancellation. */ event OrderCancelled(uint256 indexed orderId, address indexed owner, uint256 refundAmount, address sender); /** * @notice Emitted when an expired order is reclaimed. * @param orderId The id of the expired order. * @param owner The order owner that was refunded. * @param refundAmount The amount refunded to the owner. * @param sender The account that triggered the reclaim. */ event OrderExpired(uint256 indexed orderId, address indexed owner, uint256 refundAmount, address sender); /** * @notice Emitted when a market is created or updated. * @param shareToken The share token whose market was updated. * @param enabled Whether the market is enabled. * @param partitionId The configured partition. * @param requiredPrivileges The configured required privileges. * @param sender The account that updated the market. */ event MarketUpdated( address indexed shareToken, bool enabled, bytes32 partitionId, bytes32 requiredPrivileges, address indexed sender ); /** * @notice Emitted when the {withdrawTo} address is updated. * @param prevTo The previous withdrawTo address. * @param newTo The new withdrawTo address. * @param sender The account that triggered the update. */ event WithdrawToUpdated(address prevTo, address newTo, address indexed sender); /** * @notice Emitted when the {settlementFunder} address is updated. * @param prevFunder The previous settlementFunder address. * @param newFunder The new settlementFunder address. * @param sender The account that triggered the update. */ event SettlementFunderUpdated(address prevFunder, address newFunder, address indexed sender); /** * @notice Emitted when the {minSettlementWindow} is updated. * @param prevWindow The previous settlement window. * @param newWindow The new settlement window. * @param sender The account that triggered the update. */ event MinSettlementWindowUpdated(uint48 prevWindow, uint48 newWindow, address indexed sender); /** * @notice Emitted when settled stablecoin is withdrawn to {withdrawTo}. * @param amount The amount withdrawn. * @param to The destination (the withdrawTo address). * @param sender The account that triggered the withdrawal. */ event Withdrawn(uint256 amount, address indexed to, address indexed sender); /** * @notice Returns the escrow's GLOBAL_ADMIN_ROLE. Equivalent to keccak256('SomaEscrow.GLOBAL_ADMIN_ROLE'). */ function GLOBAL_ADMIN_ROLE() external pure returns (bytes32); /** * @notice Returns the escrow's instance-specific LOCAL_ADMIN_ROLE. */ function LOCAL_ADMIN_ROLE() external view returns (bytes32); /** * @notice Returns the escrow's GLOBAL_OPERATOR_ROLE. Equivalent to keccak256('SomaEscrow.GLOBAL_OPERATOR_ROLE'). */ function GLOBAL_OPERATOR_ROLE() external pure returns (bytes32); /** * @notice Returns the escrow's instance-specific LOCAL_OPERATOR_ROLE. */ function LOCAL_OPERATOR_ROLE() external view returns (bytes32); /** * @notice The escrowed stablecoin asset (e.g. USDC). */ function asset() external view returns (address); /** * @notice The destination for settled (filled buy) stablecoin. */ function withdrawTo() external view returns (address); /** * @notice The treasury address that funds sell payouts (holds a standing stablecoin approval to the escrow). */ function settlementFunder() external view returns (address); /** * @notice The settlement window that must remain before an order's expiry for an operator to lock it. * An order cannot be locked (and its capital committed off-chain) unless at least this much time * remains until expiry, guaranteeing the operator can settle before the owner's guaranteed withdrawal time. */ function minSettlementWindow() external view returns (uint48); /** * @notice The stablecoin still owed to owners: the sum of the unfilled remainder * (`amountIn - filledIn`) over all OPEN and LOCKED buy orders. Each fill releases the portion it * consumes, so this shrinks as an order fills rather than only at completion. */ function totalStableEscrowed() external view returns (uint256); /** * @notice The shares still owed to owners for a given share token: the sum of the unfilled * remainder (`amountIn - filledIn`) over all OPEN and LOCKED sell orders. */ function totalSharesEscrowed(address shareToken) external view returns (uint256); /** * @notice The id that will be assigned to the next placed order. */ function nextOrderId() external view returns (uint256); /** * @notice Returns the order with the given id. */ function orderOf(uint256 orderId) external view returns (Order memory); /** * @notice Returns the market configuration for a given share token. */ function marketOf(address shareToken) external view returns (Market memory); /** * @notice Initializes the escrow. * @param asset The escrowed stablecoin. * @param withdrawTo The destination for settled buy proceeds. * @param settlementFunder The treasury that funds sell payouts. * @param minSettlementWindow The settlement window required before expiry to lock an order. */ function initialize(address asset, address withdrawTo, address settlementFunder, uint48 minSettlementWindow) external; /** * @notice Creates or updates a market. On enable, token recovery is disabled for the share token so * escrowed sell shares cannot be swept. * @custom:requirement The caller must have the GLOBAL_ADMIN_ROLE or LOCAL_ADMIN_ROLE. * @custom:emits MarketUpdated */ function setMarket(address shareToken, bool enabled, bytes32 partitionId, bytes32 requiredPrivileges) external; /** * @notice Sets the {withdrawTo} address. * @custom:emits WithdrawToUpdated */ function setWithdrawTo(address account) external; /** * @notice Sets the {settlementFunder} address. * @custom:emits SettlementFunderUpdated */ function setSettlementFunder(address account) external; /** * @notice Sets the {minSettlementWindow}. * @custom:emits MinSettlementWindowUpdated */ function setMinSettlementWindow(uint48 newMinSettlementWindow) external; /** * @notice Places a buy order, escrowing `amountIn` stablecoin. * @param shareToken The share token to buy. Its market must be enabled. * @param amountIn The stablecoin to escrow — the most that can be spent. * @param minSharesOut The slippage floor for spending the whole `amountIn`, i.e. a cap of * `amountIn / minSharesOut` stablecoin per share. Partial fills are held to a pro-rata share of it. * @param targetSharesOut The share quantity the owner wants. Once delivered, the order completes and any * unspent stablecoin is refunded. Pass 0 to spend the whole `amountIn` instead. To escrow a budget * larger than the target's expected cost, set `minSharesOut` to `amountIn / worstAcceptablePrice` — * which will exceed `targetSharesOut`, and is allowed. * @param orderType The order type (metadata for the off-chain operator). * @param triggerPrice The limit/stop reference price, stablecoin-per-share scaled 1e18 (metadata). * @param expiry The owner's guaranteed withdrawal deadline. * @custom:emits OrderPlaced * @return orderId The id of the created order. */ function placeBuyOrder( address shareToken, uint256 amountIn, uint256 minSharesOut, uint256 targetSharesOut, OrderType orderType, uint256 triggerPrice, uint48 expiry ) external returns (uint256 orderId); /** * @notice Places a sell order, escrowing `sharesIn` share tokens. * @param shareToken The share token to sell. Its market must be enabled. * @param sharesIn The shares to escrow — the most that can be sold. * @param minStableOut The slippage floor for selling all of `sharesIn`, i.e. a floor of * `minStableOut / sharesIn` stablecoin per share. Partial fills are held to a pro-rata share of it. * @param targetStableOut The stablecoin proceeds the owner wants. Once raised, the order completes and * any unsold shares are refunded. Pass 0 to sell the whole `sharesIn` instead. May be below * `minStableOut` — that is the normal encoding when escrowing more shares than you expect to sell. * @param orderType The order type (metadata for the off-chain operator). * @param triggerPrice The limit/stop reference price, stablecoin-per-share scaled 1e18 (metadata). * @param expiry The owner's guaranteed withdrawal deadline. * @custom:emits OrderPlaced * @return orderId The id of the created order. */ function placeSellOrder( address shareToken, uint256 sharesIn, uint256 minStableOut, uint256 targetStableOut, OrderType orderType, uint256 triggerPrice, uint48 expiry ) external returns (uint256 orderId); /** * @notice Locks an OPEN order ahead of an off-chain trade so its owner cannot cancel it. Can only be * called while at least {minSettlementWindow} remains before the order's expiry, so the operator is * guaranteed to be able to settle before the owner's guaranteed withdrawal time. Locking never extends * the order past its expiry; the owner can still reclaim at expiry. * @dev A lock covers the order's whole unfilled remainder and is released by the next fill that does not * complete the order — it protects the tranche being traded, not the rest of the order. An operator * working an order in tranches must therefore re-lock before each one, and should expect {lockOrder} to * revert `NOT OPEN` if the owner cancelled in between. A lock also expires on its own after * {minSettlementWindow}; past that the owner may cancel even though the status is still LOCKED. * @param orderId The id of the order to lock. * @custom:requirement The caller must have the operator role. * @custom:emits OrderLocked */ function lockOrder(uint256 orderId) external; /** * @notice Returns a LOCKED order to OPEN (e.g. the off-chain trade was aborted). A fill that leaves the * order live releases the lock automatically, so this is only needed to abandon a tranche unfilled. * @param orderId The id of the order to unlock. * @custom:requirement The caller must have the operator role. * @custom:emits OrderUnlocked */ function unlockOrder(uint256 orderId) external; /** * @notice Fills part (or all) of a buy order: consumes `stableIn` of the escrowed stablecoin, mints * `sharesOut` of the share token and delivers them to the owner. Can be called repeatedly until the * order's target is reached or its stablecoin is exhausted, at which point the order completes and any * unspent stablecoin is refunded. * @param orderId The id of the buy order to fill. * @param stableIn The escrowed stablecoin consumed by this fill. * @param sharesOut The number of shares delivered to the owner by this fill. * @param feeAmount The commission collected on this fill (stablecoin units, already included in * `stableIn`). Recorded in {OrderFilled} for off-chain accounting only — never enforced, moves no funds. * @custom:requirement The caller must have the operator role. * @custom:requirement `stableIn` and `sharesOut` must both be non-zero. * @custom:requirement `stableIn` must not exceed the order's unfilled remainder. * @custom:requirement `sharesOut` must be >= the pro-rata share of the order's minAmountOut earned by * `stableIn`, so this fill on its own clears the owner's rate. * @custom:requirement `sharesOut` must not push the cumulative output above `targetAmountOut`. * @custom:emits OrderFilled * @custom:emits OrderCompleted when this fill finishes the order. */ function fulfillBuy(uint256 orderId, uint256 stableIn, uint256 sharesOut, uint256 feeAmount) external; /** * @notice Fills part (or all) of a sell order: burns `sharesIn` of the escrowed shares and pays * `stableOut` stablecoin to the owner. Can be called repeatedly until the order's target is reached or * its shares are exhausted, at which point the order completes and any unsold shares are refunded. * @param orderId The id of the sell order to fill. * @param sharesIn The escrowed shares consumed by this fill. * @param stableOut The stablecoin paid to the owner by this fill. * @param feeAmount The commission collected on this fill (stablecoin units, already deducted from * `stableOut`). Recorded in {OrderFilled} for off-chain accounting only — never enforced, moves no funds. * @custom:requirement The caller must have the operator role. * @custom:requirement `sharesIn` and `stableOut` must both be non-zero. * @custom:requirement `sharesIn` must not exceed the order's unfilled remainder. * @custom:requirement `stableOut` must be >= the pro-rata share of the order's minAmountOut earned by * `sharesIn`. * @custom:requirement `stableOut` must not push the cumulative output above `targetAmountOut`. * @custom:emits OrderFilled * @custom:emits OrderCompleted when this fill finishes the order. */ function fulfillSell(uint256 orderId, uint256 sharesIn, uint256 stableOut, uint256 feeAmount) external; /** * @notice Completes a partially filled order early, refunding the unfilled remainder to the owner. This * is the operator's "the rest of this order will not fill" signal — for example a limit order the market * moved away from, or a remainder too small to trade. * @param orderId The id of the order to close. * @custom:requirement The caller must have the operator role. * @dev Unlike the owner's refund paths ({cancelOrder}, {reclaimExpired}) this is an operator power, so * it is pausable — the emergency brake must be able to stop it. It carries no expiry check: closing a * partially filled order after its expiry is allowed and settles it as FILLED rather than EXPIRED. The * owner is refunded identically either way. * @custom:requirement The order must be OPEN or LOCKED and have at least one fill against it. Note this * is a weak guard, not a real restriction: a one-wei fill satisfies it, so an operator can in practice * terminate any order it chooses. Treat {closeOrder} as an operator cancel power, and note that it emits * {OrderCompleted} with status FILLED — off-chain accounting must not read that as a genuine execution * without checking `filledIn`. * @custom:requirement The contract must not be paused. * @custom:emits OrderCompleted */ function closeOrder(uint256 orderId) external; /** * @notice Cancels an order and refunds the owner's unfilled remainder. * @dev Permitted while the order is OPEN, or while it is LOCKED but its lock has gone stale * (`block.timestamp >= lockedUntil`). Capping a lock at one {minSettlementWindow} means an operator * that locks and abandons an order cannot withhold the owner's cancel until expiry. It does NOT defeat * an operator that deliberately re-locks ahead of each cancel attempt in the same block — against that, * `expiry` and {reclaimExpired} remain the owner's guaranteed exit. * @param orderId The id of the order to cancel. * @custom:requirement The caller must be the order owner. * @custom:emits OrderCancelled */ function cancelOrder(uint256 orderId) external; /** * @notice Reclaims an expired order and refunds the owner. Callable by anyone once the order's * `expiry` has passed, whether the order is OPEN or LOCKED. * @param orderId The id of the order to reclaim. * @custom:emits OrderExpired */ function reclaimExpired(uint256 orderId) external; /** * @notice Cancels an OPEN or LOCKED order and refunds the owner (emergency admin action). * @param orderId The id of the order to cancel. * @custom:requirement The caller must have the GLOBAL_ADMIN_ROLE or LOCAL_ADMIN_ROLE. * @custom:emits OrderCancelled */ function adminCancel(uint256 orderId) external; /** * @notice The amount of `token` owed to `owner` from a refund that could not be delivered, collectable * via {claim}. */ function claimableOf(address owner, address token) external view returns (uint256); /** * @notice The total of `token` owed across all deferred refunds. {withdraw} reserves this so deferred * refunds are never mistaken for desk revenue. */ function totalClaimable(address token) external view returns (uint256); /** * @notice Collects a refund that could not be delivered when its order ended. Callable by the owed * account once whatever blocked the original transfer has been lifted. * @param token The token to collect. * @custom:requirement The caller must be owed a non-zero balance of `token`. * @custom:emits RefundClaimed * @return amount The amount transferred. */ function claim(address token) external returns (uint256 amount); /** * @notice Withdraws settled stablecoin to {withdrawTo}. Cannot reduce the balance below the amount * backing OPEN/LOCKED buy orders plus any deferred refunds. * @param amount The amount of stablecoin to withdraw. * @custom:requirement The caller must have the GLOBAL_ADMIN_ROLE or LOCAL_ADMIN_ROLE. * @custom:emits Withdrawn */ function withdraw(uint256 amount) external; }