// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; /* * StillsizeSettlement — non-custodial OTC settlement for signed offers. * * - A maker signs an EIP-712 Offer off-chain (free). Nothing moves. * - A taker calls fill(); the contract checks the signature and terms and * swaps token <-> ETH/WETH atomically in the same transaction. * - Fee: FEE_BPS (0.25 %) paid by the taker, a constant that cannot change. * - Makers cancel one offer with cancel(), or every offer with incrementEpoch(). * * Trust notes: * - The contract holds no balances between transactions. * - feedAdmin can only register Chainlink feeds. A bad feed can at most make a * *guarded* offer unfillable (it can never move funds). * - Fee-on-transfer / rebasing tokens are not supported: the taker would * receive less than `amount`. * * STATUS: reference implementation, NOT AUDITED. Do not deploy with real funds * before a professional audit and a full test suite. */ import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol"; import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; interface AggregatorV3Interface { function decimals() external view returns (uint8); function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound); } contract StillsizeSettlement is EIP712, ReentrancyGuard { using SafeERC20 for IERC20; /* ------------------------------------------------------------------ */ /* Types */ /* ------------------------------------------------------------------ */ struct Offer { address maker; // signer; gives tokens (ask) or WETH (bid) address taker; // address(0) = anyone, otherwise a private offer address token; // ERC-20 being traded bool isAsk; // true: maker sells token for ETH. false: maker buys token with WETH uint256 amount; // total token amount (base units) uint256 price; // total price for `amount`, in wei uint256 minFill; // smallest slice allowed; == amount means whole-bag only uint16 guardBps; // 0 = off; otherwise max deviation from Chainlink price uint256 nonce; // random salt so identical offers have distinct hashes uint256 epoch; // must equal epochOf[maker]; bump to cancel everything uint64 expiry; // unix seconds } bytes32 public constant OFFER_TYPEHASH = keccak256( "Offer(address maker,address taker,address token,bool isAsk,uint256 amount,uint256 price,uint256 minFill,uint16 guardBps,uint256 nonce,uint256 epoch,uint64 expiry)" ); /* ------------------------------------------------------------------ */ /* Storage */ /* ------------------------------------------------------------------ */ uint256 public constant FEE_BPS = 25; // 0.25 % uint256 private constant BPS = 10_000; IERC20 public immutable WETH; address public immutable feeRecipient; address public immutable feedAdmin; AggregatorV3Interface public immutable ethUsdFeed; uint256 public immutable maxOracleAge; mapping(address token => AggregatorV3Interface) public usdFeed; mapping(bytes32 offerHash => uint256) public filled; mapping(bytes32 offerHash => bool) public cancelled; mapping(address maker => uint256) public epochOf; /* ------------------------------------------------------------------ */ /* Events */ /* ------------------------------------------------------------------ */ event Filled( bytes32 indexed offerHash, address indexed maker, address indexed taker, address token, bool isAsk, uint256 tokenAmount, uint256 ethAmount, uint256 fee ); event Cancelled(bytes32 indexed offerHash, address indexed maker); event EpochIncremented(address indexed maker, uint256 newEpoch); event FeedSet(address indexed token, address feed); /* ------------------------------------------------------------------ */ /* Errors */ /* ------------------------------------------------------------------ */ error Expired(); error NotTaker(); error StaleEpoch(); error OfferCancelled(); error BadSignature(); error BadAmount(); error BadValue(); error OutOfGuard(); error OracleUnavailable(); error NotMaker(); error NotAdmin(); error EthTransferFailed(); constructor( address weth, address feeRecipient_, address feedAdmin_, address ethUsdFeed_, uint256 maxOracleAge_ ) EIP712("Stillsize", "1") { WETH = IERC20(weth); feeRecipient = feeRecipient_; feedAdmin = feedAdmin_; ethUsdFeed = AggregatorV3Interface(ethUsdFeed_); maxOracleAge = maxOracleAge_; } /* ------------------------------------------------------------------ */ /* Fill */ /* ------------------------------------------------------------------ */ /// @notice Take `fillAmount` tokens of a signed offer. /// @dev Ask: send exactly ethFor(o, fillAmount) + fee as msg.value. /// Bid: msg.value must be 0; taker must have approved `token`. function fill(Offer calldata o, bytes calldata signature, uint256 fillAmount) external payable nonReentrant { bytes32 h = hashOffer(o); if (block.timestamp > o.expiry) revert Expired(); if (o.taker != address(0) && o.taker != msg.sender) revert NotTaker(); if (o.epoch != epochOf[o.maker]) revert StaleEpoch(); if (cancelled[h]) revert OfferCancelled(); if (!SignatureChecker.isValidSignatureNow(o.maker, h, signature)) revert BadSignature(); uint256 left = o.amount - filled[h]; // reverts on underflow if over-filled (cannot happen) if (o.amount == 0 || fillAmount == 0 || fillAmount > left) revert BadAmount(); // A slice must respect minFill, except the final remainder of the bag. if (fillAmount < o.minFill && fillAmount != left) revert BadAmount(); if (o.guardBps != 0) _checkGuard(o); filled[h] = o.amount - left + fillAmount; IERC20 token = IERC20(o.token); uint256 ethAmount; uint256 fee; if (o.isAsk) { // Taker pays: round in the maker's favour. ethAmount = Math.mulDiv(o.price, fillAmount, o.amount, Math.Rounding.Ceil); fee = Math.mulDiv(ethAmount, FEE_BPS, BPS, Math.Rounding.Ceil); if (msg.value != ethAmount + fee) revert BadValue(); token.safeTransferFrom(o.maker, msg.sender, fillAmount); _sendEth(o.maker, ethAmount); _sendEth(feeRecipient, fee); } else { // Maker pays WETH: round in the maker's favour. if (msg.value != 0) revert BadValue(); ethAmount = Math.mulDiv(o.price, fillAmount, o.amount, Math.Rounding.Floor); fee = Math.mulDiv(ethAmount, FEE_BPS, BPS, Math.Rounding.Ceil); token.safeTransferFrom(msg.sender, o.maker, fillAmount); WETH.safeTransferFrom(o.maker, msg.sender, ethAmount - fee); WETH.safeTransferFrom(o.maker, feeRecipient, fee); } emit Filled(h, o.maker, msg.sender, o.token, o.isAsk, fillAmount, ethAmount, fee); } /* ------------------------------------------------------------------ */ /* Cancel */ /* ------------------------------------------------------------------ */ function cancel(Offer calldata o) external { if (msg.sender != o.maker) revert NotMaker(); bytes32 h = hashOffer(o); cancelled[h] = true; emit Cancelled(h, msg.sender); } /// @notice Void every offer signed under the current epoch. function incrementEpoch() external { uint256 e = ++epochOf[msg.sender]; emit EpochIncremented(msg.sender, e); } /* ------------------------------------------------------------------ */ /* Admin */ /* ------------------------------------------------------------------ */ /// @notice Register a token/USD Chainlink feed for the oracle guard. function setFeed(address token, address feed) external { if (msg.sender != feedAdmin) revert NotAdmin(); usdFeed[token] = AggregatorV3Interface(feed); emit FeedSet(token, feed); } /* ------------------------------------------------------------------ */ /* Views */ /* ------------------------------------------------------------------ */ function hashOffer(Offer calldata o) public view returns (bytes32) { return _hashTypedDataV4( keccak256( abi.encode( OFFER_TYPEHASH, o.maker, o.taker, o.token, o.isAsk, o.amount, o.price, o.minFill, o.guardBps, o.nonce, o.epoch, o.expiry ) ) ); } function remaining(Offer calldata o) external view returns (uint256) { bytes32 h = hashOffer(o); if (cancelled[h] || o.epoch != epochOf[o.maker] || block.timestamp > o.expiry) return 0; return o.amount - filled[h]; } /// @notice Chainlink price of one whole token, in wei. function oraclePriceWei(address token) public view returns (uint256) { AggregatorV3Interface f = usdFeed[token]; if (address(f) == address(0)) revert OracleUnavailable(); uint256 tokenUsd = _read(f); uint256 ethUsd = _read(ethUsdFeed); // price_wei = tokenUsd / ethUsd * 1e18, normalising both feeds' decimals return Math.mulDiv(tokenUsd * 1e18, 10 ** ethUsdFeed.decimals(), ethUsd * 10 ** f.decimals()); } /* ------------------------------------------------------------------ */ /* Internals */ /* ------------------------------------------------------------------ */ function _checkGuard(Offer calldata o) internal view { uint8 dec = IERC20Metadata(o.token).decimals(); uint256 implied = Math.mulDiv(o.price, 10 ** dec, o.amount); // wei per whole token uint256 oracle = oraclePriceWei(o.token); uint256 dev = implied > oracle ? implied - oracle : oracle - implied; if (dev * BPS > uint256(o.guardBps) * oracle) revert OutOfGuard(); } function _read(AggregatorV3Interface f) internal view returns (uint256) { (, int256 answer,, uint256 updatedAt,) = f.latestRoundData(); if (answer <= 0 || block.timestamp - updatedAt > maxOracleAge) revert OracleUnavailable(); return uint256(answer); } function _sendEth(address to, uint256 value) internal { if (value == 0) return; (bool ok,) = to.call{value: value}(""); if (!ok) revert EthTransferFailed(); } }