Skip to content
Verified contractExactMIT

LatticePoints

Address0xdde7517a7a5c0067df8ee37ff43f540bd305b8aa
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 300 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,371,577
Creation transaction
0x50923724cf…9c71f611a3

<stdin>

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

interface IERC20P {
    function balanceOf(address) external view returns (uint256);
}

/// LatticePoints — a pre-market for points that are not a token yet (a protocol's points farmed now,
/// turned into its token at a launch later).
///
/// A market is one project's points (made by the settler: a name and a date its token must be set by).
/// An offer sells or buys an amount of its points for a price in the chain's coin or one ERC20. Both
/// sides lock as much as the price: the buyer the price, the seller the same again as collateral. When
/// the token exists, the settler names it and how many of its smallest units one point is worth; that
/// takes effect TOKEN_DELAY later (anyone can check it first), and from then the seller has
/// DELIVERY_WINDOW to deliver the tokens to the buyer through this contract:
///
///   delivered in time  → the seller gets the price (less FEE_BPS) and their collateral back
///   not delivered      → the buyer gets the price back and the collateral, less FORFEIT_BPS of it
///   no token by the market's date, or the market cancelled by the settler before its token took
///   effect             → both get back what they locked
///
/// A take names the terms it agrees to (`terms`, the hash of the offer as created), so a take can
/// never land on a different offer than the one read — ids are sequential and a pending `create` can
/// be reordered.
///
/// Nothing a party is owed can be held hostage by the other party: every payout is pushed if the
/// recipient takes it and credited (withdraw) if it doesn't, and delivered tokens go through this
/// contract's balance, so a buyer that refuses tokens can't turn a delivery into a forfeit.
///
/// TRUST: the settler is an oracle. Whoever holds the role decides, per market, which token the points
/// became and at what rate — a wrong rate makes every seller forfeit (and pays FORFEIT_BPS of all
/// collateral to the fee address) or lets them deliver dust. TOKEN_DELAY gives traders a day to see the
/// rate before it binds, but a matched trade has no exit. Hold the role with a multisig behind a
/// timelock, and keep it apart from the fee address. The settler can never move what an offer holds
/// directly. Fees are credited, never pushed. Both roles are handed on in two steps.
///
/// Not supported: partial fills, fee-on-transfer or rebasing tokens as payment or as the token the
/// points become (the escrow checks exactly what arrives), a token on another chain than this contract's.
contract LatticePoints {
    enum Side { SELL, BUY }                         // what the maker does with the points
    enum Status { NONE, OPEN, MATCHED, SETTLED, FORFEITED, REFUNDED, CANCELLED }

    struct Market {
        string name;
        uint64 settleBy;       // its token must take effect by then, or every trade is refunded
        uint64 tokenAt;        // when the named token takes effect (0: none named)
        bool cancelled;
        address token;         // what the points became
        uint256 perPoint;      // the token's smallest units one point is worth (points carry 18 decimals)
    }

    struct Offer {
        uint256 market;
        address maker;
        Side side;
        Status status;
        uint64 expiry;         // an open offer can be taken until then
        address seller;        // set when it is taken (the maker for a SELL offer)
        address buyer;
        address asset;         // address(0): the chain's coin
        uint256 points;        // 18 decimals
        uint256 price;         // what the buyer pays, and what the seller locks as collateral
        bytes32 terms;         // hashTerms(...) of the offer as created — what a take must agree to
    }

    uint256 public constant FEE_BPS = 50;              // 0.5% of the price, when the seller delivers
    uint256 public constant FORFEIT_BPS = 1000;        // 10% of a forfeited collateral
    uint256 public constant TOKEN_DELAY = 1 days;      // a named token takes effect this much later
    uint256 public constant DELIVERY_WINDOW = 72 hours; // from then, the seller has this long
    uint256 public constant MAX_SETTLE = 730 days;     // a market's date at most this far ahead

    address public feeTo;
    address public pendingFeeTo;
    address public settler;
    address public pendingSettler;

    Market[] private _markets;
    uint256 public nextId = 1;
    mapping(uint256 => Offer) private _offers;
    mapping(address => mapping(address => uint256)) public owed;   // account -> asset (0: coin) -> amount

    uint256[] private _open;                         // offers open to take (in no particular order)
    mapping(uint256 => uint256) private _openAt;     // id -> index in _open + 1

    uint256 private _lock = 1;

    event MarketMade(uint256 indexed market, string name, uint64 settleBy);
    event TokenNamed(uint256 indexed market, address token, uint256 perPoint, uint64 takesEffect);
    event MarketCancelled(uint256 indexed market);
    event Created(uint256 indexed id, uint256 indexed market, address indexed maker, Side side, bytes32 terms);
    event Cancelled(uint256 indexed id);
    event Matched(uint256 indexed id, address indexed seller, address indexed buyer);
    event Delivered(uint256 indexed id, uint256 tokens, uint256 fee);
    event Forfeited(uint256 indexed id, uint256 toBuyer, uint256 fee);
    event Refunded(uint256 indexed id);
    event Credited(address indexed to, address indexed asset, uint256 amount);   // a push refused, kept for withdraw
    event RoleOffered(bytes32 indexed role, address indexed to);
    event RoleSet(bytes32 indexed role, address indexed to);

    error BadInput();
    error BadValue();
    error BadTerms();
    error NotOpen();
    error NotMatched();
    error NotYours();
    error MarketClosed();
    error TooEarly();
    error TooLate();
    error ShortDelivery();
    error TransferFailed();
    error Reentrancy();
    error NotAllowed();

    modifier nonReentrant() {
        if (_lock != 1) revert Reentrancy();
        _lock = 2;
        _;
        _lock = 1;
    }

    constructor(address feeTo_, address settler_) {
        feeTo = feeTo_;
        settler = settler_;
        emit RoleSet("fee", feeTo_);
        emit RoleSet("settler", settler_);
    }

    // ------------------------------------------------------------------ settler

    function makeMarket(string calldata name, uint64 settleBy) external returns (uint256 market) {
        if (msg.sender != settler) revert NotAllowed();
        if (bytes(name).length == 0 || bytes(name).length > 64 || settleBy <= block.timestamp
            || settleBy > block.timestamp + MAX_SETTLE) revert BadInput();
        market = _markets.length;
        Market storage m = _markets.push();
        (m.name, m.settleBy) = (name, settleBy);
        emit MarketMade(market, name, settleBy);
    }

    /// Name the token the points became and what one point is worth in it. It takes effect TOKEN_DELAY
    /// later (and must, before the market's date); until then it can be named again (the delay starts
    /// over). Once in effect it's final.
    function nameToken(uint256 market, address token, uint256 perPoint) external {
        if (msg.sender != settler) revert NotAllowed();
        Market storage m = _market(market);
        if (m.cancelled || (m.tokenAt != 0 && block.timestamp >= m.tokenAt)) revert MarketClosed();
        uint64 at = uint64(block.timestamp + TOKEN_DELAY);
        if (token.code.length == 0 || perPoint == 0 || at > m.settleBy) revert BadInput();
        (m.token, m.perPoint, m.tokenAt) = (token, perPoint, at);
        emit TokenNamed(market, token, perPoint, at);
    }

    /// No token is coming: every trade of the market can be refunded. Only before a token took effect.
    function cancelMarket(uint256 market) external {
        if (msg.sender != settler) revert NotAllowed();
        Market storage m = _market(market);
        if (m.cancelled || (m.tokenAt != 0 && block.timestamp >= m.tokenAt)) revert MarketClosed();
        m.cancelled = true;
        emit MarketCancelled(market);
    }

    // ------------------------------------------------------------------ traders

    /// Sell (side SELL: lock `price` as collateral) or buy (side BUY: lock `price`) `points` of a market
    /// for `price` of `asset` (0: the coin, as msg.value), open until `expiry`.
    function create(uint256 market, Side side, uint256 points, address asset, uint256 price, uint64 expiry)
        external payable nonReentrant returns (uint256 id)
    {
        if (!_trading(_market(market))) revert MarketClosed();
        if (points == 0 || price == 0 || expiry <= block.timestamp) revert BadInput();
        if (asset != address(0) && asset.code.length == 0) revert BadInput();
        id = nextId++;
        Offer storage o = _offers[id];
        o.market = market;
        o.maker = msg.sender;
        o.side = side;
        o.expiry = expiry;
        o.asset = asset;
        o.points = points;
        o.price = price;
        bytes32 terms = hashTerms(market, msg.sender, side, points, asset, price, expiry);
        o.terms = terms;
        _pullIn(asset, price);
        if (side == Side.SELL) o.seller = msg.sender;
        else o.buyer = msg.sender;
        o.status = Status.OPEN;   // last: nothing observed during the pull looks like an open offer
        _open.push(id);
        _openAt[id] = _open.length;
        emit Created(id, market, msg.sender, side, terms);
    }

    /// The maker takes back an offer nobody took — any time. Anyone may do it for them once the offer
    /// has expired or its market stopped trading (it can't be taken any more, so this only tidies up).
    function cancel(uint256 id) external nonReentrant {
        Offer storage o = _offers[id];
        if (o.status != Status.OPEN) revert NotOpen();
        if (msg.sender != o.maker && block.timestamp < o.expiry && _trading(_markets[o.market])) revert NotYours();
        o.status = Status.CANCELLED;
        _unlist(id);
        _payOut(o.asset, o.maker, o.price);
        emit Cancelled(id);
    }

    /// Take an open offer: lock the other side (the price, or the same as collateral). `terms` is the
    /// offer's hash as read (offer(id).terms): the take reverts if the offer at `id` is any other.
    function take(uint256 id, bytes32 terms) external payable nonReentrant {
        Offer storage o = _offers[id];
        if (o.status != Status.OPEN) revert NotOpen();
        if (o.terms != terms) revert BadTerms();
        if (block.timestamp >= o.expiry || !_trading(_markets[o.market])) revert TooLate();
        if (msg.sender == o.maker) revert NotYours();
        o.status = Status.MATCHED;
        _unlist(id);
        if (o.side == Side.SELL) o.buyer = msg.sender;
        else o.seller = msg.sender;
        _pullIn(o.asset, o.price);
        emit Matched(id, o.seller, o.buyer);
    }

    /// The seller delivers the tokens to the buyer, inside the window: they get the price (less the fee)
    /// and their collateral back. The tokens pass through this contract, so the buyer can't refuse
    /// them to force a forfeit: what the buyer's address won't take is credited to it (withdraw).
    function deliver(uint256 id) external nonReentrant {
        Offer storage o = _offers[id];
        if (o.status != Status.MATCHED) revert NotMatched();
        if (msg.sender != o.seller) revert NotYours();
        Market storage m = _markets[o.market];
        if (m.cancelled || m.tokenAt == 0 || block.timestamp < m.tokenAt) revert TooEarly();
        if (block.timestamp >= m.tokenAt + DELIVERY_WINDOW) revert TooLate();
        o.status = Status.SETTLED;
        uint256 tokens = tokensFor(o.market, o.points);
        uint256 before = IERC20P(m.token).balanceOf(address(this));
        _erc20Call(m.token, abi.encodeWithSelector(0x23b872dd, o.seller, address(this), tokens));
        if (IERC20P(m.token).balanceOf(address(this)) - before < tokens) revert ShortDelivery();
        _payOut(m.token, o.buyer, tokens);
        uint256 fee = feeTo == address(0) ? 0 : o.price * FEE_BPS / 10_000;
        if (fee != 0) owed[feeTo][o.asset] += fee;
        _payOut(o.asset, o.seller, 2 * o.price - fee);
        emit Delivered(id, tokens, fee);
    }

    /// After the window, anyone: the buyer gets the price back and the collateral, less FORFEIT_BPS.
    function forfeit(uint256 id) external nonReentrant {
        Offer storage o = _offers[id];
        if (o.status != Status.MATCHED) revert NotMatched();
        Market storage m = _markets[o.market];
        if (m.cancelled || m.tokenAt == 0 || block.timestamp < m.tokenAt + DELIVERY_WINDOW) revert TooEarly();
        o.status = Status.FORFEITED;
        uint256 fee = feeTo == address(0) ? 0 : o.price * FORFEIT_BPS / 10_000;
        if (fee != 0) owed[feeTo][o.asset] += fee;
        _payOut(o.asset, o.buyer, 2 * o.price - fee);
        emit Forfeited(id, 2 * o.price - fee, fee);
    }

    /// A market cancelled, or its date passed with no token in effect: anyone sends each side back
    /// what it locked.
    function refund(uint256 id) external nonReentrant {
        Offer storage o = _offers[id];
        if (o.status != Status.MATCHED) revert NotMatched();
        if (!refundable(o.market)) revert TooEarly();
        o.status = Status.REFUNDED;
        _payOut(o.asset, o.buyer, o.price);
        _payOut(o.asset, o.seller, o.price);
        emit Refunded(id);
    }

    /// What's credited to the caller (fees, delivered tokens, or anything a push to it failed to
    /// deliver): `asset` 0 for the coin.
    function withdraw(address asset) external nonReentrant {
        uint256 v = owed[msg.sender][asset];
        owed[msg.sender][asset] = 0;
        if (v == 0) return;
        if (asset == address(0)) {
            (bool ok, ) = msg.sender.call{value: v}("");
            if (!ok) revert TransferFailed();
        } else {
            _erc20Call(asset, abi.encodeWithSelector(0xa9059cbb, msg.sender, v));
        }
    }

    // ------------------------------------------------------------------ roles (two steps)

    function setFeeTo(address to) external {
        if (msg.sender != feeTo) revert NotAllowed();
        if (to == address(0)) { delete pendingFeeTo; feeTo = address(0); emit RoleSet("fee", address(0)); }
        else { pendingFeeTo = to; emit RoleOffered("fee", to); }
    }

    function acceptFeeTo() external {
        if (msg.sender != pendingFeeTo) revert NotAllowed();
        delete pendingFeeTo;
        feeTo = msg.sender;
        emit RoleSet("fee", msg.sender);
    }

    function setSettler(address to) external {
        if (msg.sender != settler || to == address(0)) revert NotAllowed();
        pendingSettler = to;
        emit RoleOffered("settler", to);
    }

    function acceptSettler() external {
        if (msg.sender != pendingSettler) revert NotAllowed();
        delete pendingSettler;
        settler = msg.sender;
        emit RoleSet("settler", msg.sender);
    }

    // ------------------------------------------------------------------ reads

    function marketCount() external view returns (uint256) { return _markets.length; }

    function market(uint256 i) external view returns (Market memory) { return _market(i); }

    function offer(uint256 id) external view returns (Offer memory) { return _offers[id]; }

    function openCount() external view returns (uint256) { return _open.length; }

    function openOffers(uint256 start, uint256 count) external view returns (uint256[] memory ids, Offer[] memory offers) {
        uint256 n = _open.length;
        uint256 end = start >= n ? start : (count > n - start ? n : start + count);
        ids = new uint256[](end - start);
        offers = new Offer[](end - start);
        for (uint256 i = start; i < end; ++i) {
            ids[i - start] = _open[i];
            offers[i - start] = _offers[_open[i]];
        }
    }

    /// The hash a take agrees to: the offer exactly as created.
    function hashTerms(uint256 market_, address maker, Side side, uint256 points, address asset, uint256 price, uint64 expiry)
        public pure returns (bytes32)
    {
        return keccak256(abi.encode(market_, maker, side, points, asset, price, expiry));
    }

    /// The token's smallest units `points` (18 decimals) are worth in a market, rounded up: a fraction
    /// of a unit is the seller's to cover, never the buyer's to lose (with a low rate and a small
    /// trade, rounding down would let a seller be paid for delivering nothing).
    function tokensFor(uint256 market_, uint256 points) public view returns (uint256) {
        uint256 raw = points * _markets[market_].perPoint;
        return raw / 1e18 + (raw % 1e18 == 0 ? 0 : 1);
    }

    function refundable(uint256 market_) public view returns (bool) {
        Market storage m = _markets[market_];
        // (a named token always takes effect by the market's date: nameToken refuses a later one)
        return m.cancelled || (block.timestamp >= m.settleBy && m.tokenAt == 0);
    }

    // ------------------------------------------------------------------ internals

    function _market(uint256 i) private view returns (Market storage) {
        if (i >= _markets.length) revert BadInput();
        return _markets[i];
    }

    /// Offers are made and taken only while no token is in effect, the market isn't cancelled and its
    /// date hasn't passed.
    function _trading(Market storage m) private view returns (bool) {
        return !m.cancelled && block.timestamp < m.settleBy && (m.tokenAt == 0 || block.timestamp < m.tokenAt);
    }

    /// Exactly `amount` in: the coin as msg.value, or an ERC20 pulled from the caller (what arrives must
    /// be all of it — a fee-on-transfer token is refused).
    function _pullIn(address asset, uint256 amount) private {
        if (asset == address(0)) {
            if (msg.value != amount) revert BadValue();
            return;
        }
        if (msg.value != 0) revert BadValue();
        uint256 before = IERC20P(asset).balanceOf(address(this));
        _erc20Call(asset, abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), amount));
        if (IERC20P(asset).balanceOf(address(this)) - before != amount) revert ShortDelivery();
    }

    /// Pushed; what a recipient refuses (a contract without a payable receive, a token that won't
    /// transfer to it right now) is credited (withdraw) instead of blocking. No payout ever reverts the
    /// call that makes it, so no party can hold up the other's money by being unable to receive.
    function _payOut(address asset, address to, uint256 amount) private {
        if (amount == 0) return;
        bool ok;
        if (asset == address(0)) {
            (ok, ) = to.call{value: amount}("");
        } else {
            ok = _erc20Try(asset, abi.encodeWithSelector(0xa9059cbb, to, amount));
        }
        if (!ok) {
            owed[to][asset] += amount;
            emit Credited(to, asset, amount);
        }
    }

    function _erc20Call(address token, bytes memory data) private {
        if (!_erc20Try(token, data)) revert TransferFailed();
    }

    /// SafeERC20 as a bool: tokens that return nothing (USDT), false, or something that isn't a bool.
    function _erc20Try(address token, bytes memory data) private returns (bool) {
        (bool ok, bytes memory ret) = token.call(data);
        return ok && (ret.length == 0 || (ret.length >= 32 && abi.decode(ret, (bool))));
    }

    function _unlist(uint256 id) private {
        uint256 at = _openAt[id];
        if (at == 0) return;
        uint256 last = _open[_open.length - 1];
        _open[at - 1] = last;
        _openAt[last] = at;
        _open.pop();
        delete _openAt[id];
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 300,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.