// SPDX-License-Identifier: UNLICENSED pragma solidity =0.8.18; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "../SomaGuard/utils/GuardableUpgradeable.sol"; import "../SomaGuard/ISomaGuard.sol"; import "../Lockdrop/extensions/TokenRecoveryUpgradeable.sol"; import "../SecurityTokens/extensions/IMintableSecurity.sol"; import "./ISomaEscrow.sol"; /** * @notice Implementation of the {ISomaEscrow} interface. */ contract SomaEscrow is ISomaEscrow, TokenRecoveryUpgradeable, GuardableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; /** * @notice The scale used for the {OrderFilled} effectivePrice (stablecoin-per-share). */ uint256 private constant PRICE_SCALE = 1e18; /** * @inheritdoc ISomaEscrow */ bytes32 public constant override GLOBAL_ADMIN_ROLE = keccak256("SomaEscrow.GLOBAL_ADMIN_ROLE"); /** * @inheritdoc ISomaEscrow */ bytes32 public constant override GLOBAL_OPERATOR_ROLE = keccak256("SomaEscrow.GLOBAL_OPERATOR_ROLE"); /** * @inheritdoc ISomaEscrow */ bytes32 public override LOCAL_ADMIN_ROLE; /** * @inheritdoc ISomaEscrow */ bytes32 public override LOCAL_OPERATOR_ROLE; /** * @inheritdoc ISomaEscrow */ address public override asset; /** * @inheritdoc ISomaEscrow */ address public override withdrawTo; /** * @inheritdoc ISomaEscrow */ address public override settlementFunder; /** * @inheritdoc ISomaEscrow */ uint48 public override minSettlementWindow; /** * @inheritdoc ISomaEscrow */ uint256 public override totalStableEscrowed; /** * @inheritdoc ISomaEscrow */ mapping(address => uint256) public override totalSharesEscrowed; /** * @inheritdoc ISomaEscrow */ uint256 public override nextOrderId; /** * @inheritdoc ISomaEscrow */ mapping(address => uint256) public override totalClaimable; mapping(uint256 => Order) private _orders; mapping(address => Market) private _markets; mapping(address => mapping(address => uint256)) private _claimable; /** * @notice Restricts a function to accounts with the GLOBAL_ADMIN_ROLE or LOCAL_ADMIN_ROLE. */ modifier onlyAdmin() { address sender = _msgSender(); require(hasRole(GLOBAL_ADMIN_ROLE, sender) || hasRole(LOCAL_ADMIN_ROLE, sender), "SomaEscrow: ADMIN ONLY"); _; } /** * @notice Restricts a function to accounts with the GLOBAL_OPERATOR_ROLE or LOCAL_OPERATOR_ROLE. */ modifier onlyOperator() { address sender = _msgSender(); require( hasRole(GLOBAL_OPERATOR_ROLE, sender) || hasRole(LOCAL_OPERATOR_ROLE, sender), "SomaEscrow: OPERATOR ONLY" ); _; } /** * @inheritdoc ISomaEscrow */ function initialize(address _asset, address _withdrawTo, address _settlementFunder, uint48 _minSettlementWindow) external override initializer { require(_asset != address(0), "SomaEscrow: INVALID ASSET"); LOCAL_ADMIN_ROLE = keccak256(abi.encodePacked(address(this), GLOBAL_ADMIN_ROLE)); LOCAL_OPERATOR_ROLE = keccak256(abi.encodePacked(address(this), GLOBAL_OPERATOR_ROLE)); __Guardable__init(); __ReentrancyGuard_init_unchained(); __TokenRecovery__init_unchained(new address[](0)); asset = _asset; _disableTokenRecovery(_asset); _setWithdrawTo(_withdrawTo); _setSettlementFunder(_settlementFunder); _setMinSettlementWindow(_minSettlementWindow); } /** * @notice Checks if SomaEscrow inherits a given contract interface. * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(GuardableUpgradeable, TokenRecoveryUpgradeable) returns (bool) { return interfaceId == type(ISomaEscrow).interfaceId || super.supportsInterface(interfaceId); } /** * @inheritdoc ISomaEscrow */ function orderOf(uint256 orderId) external view override returns (Order memory) { return _orders[orderId]; } /** * @inheritdoc ISomaEscrow */ function claimableOf(address owner, address token) external view override returns (uint256) { return _claimable[owner][token]; } /** * @inheritdoc ISomaEscrow */ function marketOf(address shareToken) external view override returns (Market memory) { return _markets[shareToken]; } /** * @inheritdoc ISomaEscrow */ function setMarket(address shareToken, bool enabled, bytes32 partitionId, bytes32 requiredPrivileges) external override onlyAdmin { require(shareToken != address(0), "SomaEscrow: INVALID TOKEN"); // Sell escrow for a share market is tracked in totalSharesEscrowed, which withdraw() does not // consult. Registering the asset itself would let a withdraw sweep sell-order principal. require(shareToken != asset, "SomaEscrow: INVALID TOKEN"); _markets[shareToken] = Market(enabled, partitionId, requiredPrivileges); // Protect escrowed sell shares from being swept via {recoverTokens}. if (enabled) { _disableTokenRecovery(shareToken); } emit MarketUpdated(shareToken, enabled, partitionId, requiredPrivileges, _msgSender()); } /** * @inheritdoc ISomaEscrow */ function setWithdrawTo(address account) external override onlyMasterOrSubMaster { _setWithdrawTo(account); } /** * @inheritdoc ISomaEscrow */ function setSettlementFunder(address account) external override onlyMasterOrSubMaster { _setSettlementFunder(account); } /** * @inheritdoc ISomaEscrow */ function setMinSettlementWindow(uint48 newMinSettlementWindow) external override onlyAdmin { _setMinSettlementWindow(newMinSettlementWindow); } /** * @inheritdoc ISomaEscrow */ function placeBuyOrder( address shareToken, uint256 amountIn, uint256 minSharesOut, uint256 targetSharesOut, OrderType orderType, uint256 triggerPrice, uint48 expiry ) external override whenNotPaused nonReentrant returns (uint256 orderId) { Market memory market = _validatePlacement(shareToken, amountIn, minSharesOut, expiry); uint256 prevBalance = IERC20(asset).balanceOf(address(this)); IERC20(asset).safeTransferFrom(_msgSender(), address(this), amountIn); uint256 received = IERC20(asset).balanceOf(address(this)) - prevBalance; require(received > 0, "SomaEscrow: ZERO AMOUNT"); totalStableEscrowed += received; orderId = _createOrder( shareToken, Side.BUY, orderType, received, minSharesOut, targetSharesOut, triggerPrice, expiry, market ); } /** * @inheritdoc ISomaEscrow */ function placeSellOrder( address shareToken, uint256 sharesIn, uint256 minStableOut, uint256 targetStableOut, OrderType orderType, uint256 triggerPrice, uint48 expiry ) external override whenNotPaused nonReentrant returns (uint256 orderId) { Market memory market = _validatePlacement(shareToken, sharesIn, minStableOut, expiry); uint256 prevBalance = IERC20(shareToken).balanceOf(address(this)); IERC20(shareToken).safeTransferFrom(_msgSender(), address(this), sharesIn); uint256 received = IERC20(shareToken).balanceOf(address(this)) - prevBalance; require(received > 0, "SomaEscrow: ZERO AMOUNT"); totalSharesEscrowed[shareToken] += received; orderId = _createOrder( shareToken, Side.SELL, orderType, received, minStableOut, targetStableOut, triggerPrice, expiry, market ); } /** * @inheritdoc ISomaEscrow */ function lockOrder(uint256 orderId) external override onlyOperator whenNotPaused nonReentrant { Order storage order = _orders[orderId]; require(order.status == OrderStatus.OPEN, "SomaEscrow: NOT OPEN"); // Only lock if a full settlement window still remains before the owner's guaranteed withdrawal // time, so the operator can always settle before the owner may reclaim. Never extends past expiry. require(block.timestamp + minSettlementWindow <= order.expiry, "SomaEscrow: INSUFFICIENT WINDOW"); order.status = OrderStatus.LOCKED; // The lock withholds the owner's cancel for exactly one settlement window. Past that it is stale // and the owner is free again, so an operator that locks and walks away — or a backend that // crashes mid-tranche — cannot freeze the order until expiry. uint48 lockedUntil = uint48(block.timestamp) + minSettlementWindow; order.lockedUntil = lockedUntil; emit OrderLocked(orderId, lockedUntil, _msgSender()); } /** * @inheritdoc ISomaEscrow */ function unlockOrder(uint256 orderId) external override onlyOperator nonReentrant { Order storage order = _orders[orderId]; require(order.status == OrderStatus.LOCKED, "SomaEscrow: NOT LOCKED"); order.status = OrderStatus.OPEN; order.lockedUntil = 0; emit OrderUnlocked(orderId, _msgSender()); } /** * @inheritdoc ISomaEscrow */ function fulfillBuy(uint256 orderId, uint256 stableIn, uint256 sharesOut, uint256 feeAmount) external override onlyOperator whenNotPaused nonReentrant { Order storage order = _orders[orderId]; require(order.side == Side.BUY, "SomaEscrow: NOT BUY"); _requireFillable(order); _applyFill(order, stableIn, sharesOut); // Only the consumed portion stops being owner-backed; the remainder stays escrowed for them. totalStableEscrowed -= stableIn; // Mint the shares (they land in SOMA.mintTo()) and deliver them to the owner atomically. address mintTo = SOMA.mintTo(); IMintableSecurity(order.shareToken).mint(order.partitionId, sharesOut, ""); IERC20(order.shareToken).safeTransferFrom(mintTo, order.owner, sharesOut); emit OrderFilled( orderId, order.owner, order.shareToken, Side.BUY, stableIn, sharesOut, feeAmount, _price(stableIn, sharesOut), order.filledIn, order.filledOut, _msgSender() ); _completeIfDone(orderId, order); } /** * @inheritdoc ISomaEscrow */ function fulfillSell(uint256 orderId, uint256 sharesIn, uint256 stableOut, uint256 feeAmount) external override onlyOperator whenNotPaused nonReentrant { Order storage order = _orders[orderId]; require(order.side == Side.SELL, "SomaEscrow: NOT SELL"); _requireFillable(order); _applyFill(order, sharesIn, stableOut); totalSharesEscrowed[order.shareToken] -= sharesIn; // Pay the seller from the settlement funder. IERC20(asset).safeTransferFrom(settlementFunder, order.owner, stableOut); // Remove the sold shares from supply: move to SOMA.mintTo() then burn. Unsold shares stay escrowed. address mintTo = SOMA.mintTo(); IERC20(order.shareToken).safeTransfer(mintTo, sharesIn); IMintableSecurity(order.shareToken).burn(order.partitionId, sharesIn, ""); emit OrderFilled( orderId, order.owner, order.shareToken, Side.SELL, sharesIn, stableOut, feeAmount, _price(stableOut, sharesIn), order.filledIn, order.filledOut, _msgSender() ); _completeIfDone(orderId, order); } /** * @inheritdoc ISomaEscrow */ function closeOrder(uint256 orderId) external override onlyOperator whenNotPaused nonReentrant { Order storage order = _orders[orderId]; require(order.status == OrderStatus.OPEN || order.status == OrderStatus.LOCKED, "SomaEscrow: NOT ACTIVE"); // Closing an untouched order would be an operator-side cancel; that is {adminCancel}'s job. require(order.filledIn > 0, "SomaEscrow: NOT PARTIALLY FILLED"); _complete(orderId, order); } /** * @inheritdoc ISomaEscrow */ function cancelOrder(uint256 orderId) external override nonReentrant { Order storage order = _orders[orderId]; require(order.owner == _msgSender(), "SomaEscrow: NOT OWNER"); require(_ownerMayCancel(order), "SomaEscrow: NOT CANCELLABLE"); order.status = OrderStatus.CANCELLED; uint256 refundAmount = _refund(orderId, order); emit OrderCancelled(orderId, order.owner, refundAmount, _msgSender()); } /** * @inheritdoc ISomaEscrow */ function adminCancel(uint256 orderId) external override onlyAdmin nonReentrant { Order storage order = _orders[orderId]; require(order.status == OrderStatus.OPEN || order.status == OrderStatus.LOCKED, "SomaEscrow: NOT ACTIVE"); order.status = OrderStatus.CANCELLED; uint256 refundAmount = _refund(orderId, order); emit OrderCancelled(orderId, order.owner, refundAmount, _msgSender()); } /** * @inheritdoc ISomaEscrow */ function reclaimExpired(uint256 orderId) external override nonReentrant { Order storage order = _orders[orderId]; OrderStatus status = order.status; require(status == OrderStatus.OPEN || status == OrderStatus.LOCKED, "SomaEscrow: NOT ACTIVE"); require(block.timestamp >= order.expiry, "SomaEscrow: NOT EXPIRED"); order.status = OrderStatus.EXPIRED; uint256 refundAmount = _refund(orderId, order); emit OrderExpired(orderId, order.owner, refundAmount, _msgSender()); } /** * @inheritdoc ISomaEscrow */ function claim(address token) external override nonReentrant returns (uint256 amount) { address owner = _msgSender(); amount = _claimable[owner][token]; require(amount > 0, "SomaEscrow: NOTHING TO CLAIM"); _claimable[owner][token] = 0; totalClaimable[token] -= amount; IERC20(token).safeTransfer(owner, amount); emit RefundClaimed(owner, token, amount); } /** * @inheritdoc ISomaEscrow */ function withdraw(uint256 amount) external override onlyAdmin nonReentrant { require( IERC20(asset).balanceOf(address(this)) >= amount + totalStableEscrowed + totalClaimable[asset], "SomaEscrow: BACKING" ); IERC20(asset).safeTransfer(withdrawTo, amount); emit Withdrawn(amount, withdrawTo, _msgSender()); } function _validatePlacement(address shareToken, uint256 amountIn, uint256 minAmountOut, uint48 expiry) private view returns (Market memory market) { market = _markets[shareToken]; require(market.enabled, "SomaEscrow: MARKET DISABLED"); require(amountIn > 0, "SomaEscrow: ZERO AMOUNT"); require(minAmountOut > 0, "SomaEscrow: ZERO MIN OUT"); require(expiry > block.timestamp, "SomaEscrow: INVALID EXPIRY"); require(ISomaGuard(SOMA.guard()).check(_msgSender(), market.requiredPrivileges), "SomaEscrow: NO PRIVILEGES"); } function _createOrder( address shareToken, Side side, OrderType orderType, uint256 amountIn, uint256 minAmountOut, uint256 targetAmountOut, uint256 triggerPrice, uint48 expiry, Market memory market ) private returns (uint256 orderId) { address owner = _msgSender(); orderId = nextOrderId++; _orders[orderId] = Order({ owner: owner, side: side, orderType: orderType, status: OrderStatus.OPEN, shareToken: shareToken, expiry: expiry, lockedUntil: 0, amountIn: amountIn, minAmountOut: minAmountOut, targetAmountOut: targetAmountOut, filledIn: 0, filledOut: 0, triggerPrice: triggerPrice, partitionId: market.partitionId, requiredPrivileges: market.requiredPrivileges }); emit OrderPlaced( orderId, owner, shareToken, side, orderType, amountIn, minAmountOut, targetAmountOut, triggerPrice, expiry ); } function _requireFillable(Order storage order) private view { OrderStatus status = order.status; require(status == OrderStatus.OPEN || status == OrderStatus.LOCKED, "SomaEscrow: NOT FILLABLE"); require(block.timestamp < order.expiry, "SomaEscrow: EXPIRED"); } /** * @dev Books a fill against `order` and enforces the owner's protection on both price and size. * * Price: *every* fill must independently clear the owner's rate, `minAmountOut` per `amountIn`. The * floor is deliberately applied to each increment rather than only to the running totals. A cumulative * check stops binding the moment `filledOut` reaches `minAmountOut` — its right-hand side peaks there — * which would let an operator deliver honestly once and then consume the entire remaining input for a * single wei. Per-increment implies the cumulative bound, so this is strictly stronger. * * Size: `targetAmountOut` is a hard ceiling, not merely a completion trigger. Without this an operator * could overshoot it and consume the whole input — liquidating a seller's entire holding when they asked * to raise a fraction of it, or over-sizing a buyer's position — since the completion check only runs * after the fill is booked. The last fill must therefore be sized exactly to the target. */ function _applyFill(Order storage order, uint256 amountInDelta, uint256 amountOutDelta) private { require(amountInDelta > 0 && amountOutDelta > 0, "SomaEscrow: ZERO FILL"); uint256 filledIn = order.filledIn + amountInDelta; require(filledIn <= order.amountIn, "SomaEscrow: EXCEEDS REMAINING"); // Round the floor up so rounding dust can never accrue in the operator's favour. mulDiv carries a // 512-bit intermediate, so a large user-supplied minAmountOut cannot overflow the order into being // unfillable. require( amountOutDelta >= Math.mulDiv(order.minAmountOut, amountInDelta, order.amountIn, Math.Rounding.Up), "SomaEscrow: SLIPPAGE" ); uint256 filledOut = order.filledOut + amountOutDelta; uint256 target = order.targetAmountOut; require(target == 0 || filledOut <= target, "SomaEscrow: EXCEEDS TARGET"); order.filledIn = filledIn; order.filledOut = filledOut; } /** * @dev Completes the order once it has nothing left to give: either the input is spent, or the owner has * received the quantity they asked for. Orders with no target run until the input is exhausted. */ function _completeIfDone(uint256 orderId, Order storage order) private { uint256 target = order.targetAmountOut; bool exhausted = order.filledIn == order.amountIn; bool targetReached = target > 0 && order.filledOut >= target; if (exhausted || targetReached) { _complete(orderId, order); return; } // The lock exists to stop the owner cancelling out from under the tranche the operator is actually // trading — so it dies with that tranche. Leaving it set would freeze the whole untouched remainder // until expiry off the back of a single (possibly dust) fill. The operator re-locks per tranche. if (order.status == OrderStatus.LOCKED) { order.status = OrderStatus.OPEN; order.lockedUntil = 0; emit OrderUnlocked(orderId, _msgSender()); } } function _complete(uint256 orderId, Order storage order) private { order.status = OrderStatus.FILLED; uint256 refundAmount = _refund(orderId, order); emit OrderCompleted(orderId, order.owner, order.filledIn, order.filledOut, refundAmount, _msgSender()); } /** * @dev Returns the unfilled remainder to the owner. Fills have already released their consumed portion * from the escrow totals, so only `amountIn - filledIn` is still owed. * * The transfer is attempted but never allowed to fail the transaction. A refund can be un-sendable * through no fault of the escrow: `SecurityToken` transfers are guard-gated, so a seller whose * privileges lapse cannot receive their shares, and a blocklisting stablecoin can do the same to a * buyer. Reverting here would put that on every terminal path — cancel, admin cancel, expiry reclaim * and fill completion alike — leaving the order permanently unresolvable and its funds stranded with * no rescue, since token recovery is disabled on the asset and on every enabled market token. * * So a failed transfer is booked as a claimable balance instead: the order still reaches its terminal * state, other orders are unaffected, and the owner collects via {claim} once whatever blocked them is * lifted. {withdraw} reserves the deferred amount, so it is never mistaken for desk revenue. */ function _refund(uint256 orderId, Order storage order) private returns (uint256 refundAmount) { refundAmount = order.amountIn - order.filledIn; if (refundAmount == 0) return 0; address token; if (order.side == Side.BUY) { totalStableEscrowed -= refundAmount; token = asset; } else { totalSharesEscrowed[order.shareToken] -= refundAmount; token = order.shareToken; } if (!_tryTransfer(token, order.owner, refundAmount)) { _claimable[order.owner][token] += refundAmount; totalClaimable[token] += refundAmount; emit RefundDeferred(orderId, order.owner, token, refundAmount); } } /** * @dev ERC20 transfer that reports failure instead of reverting, tolerating both the bool-returning and * the no-return-data conventions. A revert inside the token surfaces as `false`. * * Treating empty return data as success is only safe because `token` is always known to have code: an * order can only exist if {placeBuyOrder}/{placeSellOrder} first pulled the same token in via * `safeTransferFrom`, and SafeERC20 routes through `Address.functionCall`, which rejects a target * without contract code. A bare `call` to an EOA would otherwise return `(true, "")` and be misread * here as a delivered refund. */ function _tryTransfer(address token, address to, uint256 amount) private returns (bool) { (bool ok, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, amount)); if (!ok) return false; return data.length == 0 || (data.length >= 32 && abi.decode(data, (bool))); } /** * @dev The owner may cancel an OPEN order, or a LOCKED one whose lock has gone stale. Locks are capped * at one {minSettlementWindow} so a lock left set cannot withhold the cancel until expiry. */ function _ownerMayCancel(Order storage order) private view returns (bool) { OrderStatus status = order.status; if (status == OrderStatus.OPEN) return true; return status == OrderStatus.LOCKED && block.timestamp >= order.lockedUntil; } function _price(uint256 stableAmount, uint256 shareAmount) private pure returns (uint256) { return (stableAmount * PRICE_SCALE) / shareAmount; } function _setWithdrawTo(address account) private { emit WithdrawToUpdated(withdrawTo, account, _msgSender()); withdrawTo = account; } function _setSettlementFunder(address account) private { emit SettlementFunderUpdated(settlementFunder, account, _msgSender()); settlementFunder = account; } function _setMinSettlementWindow(uint48 newMinSettlementWindow) private { emit MinSettlementWindowUpdated(minSettlementWindow, newMinSettlementWindow, _msgSender()); minSettlementWindow = newMinSettlementWindow; } uint256[48] private __gap; }