Verified contractExactMIT
LatticeOTC
Address0x376516e36a183a6be46da5f86d8ae5007d7e89b3
- 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,372,952
- Creation transaction
- 0x1d5c361de1…12e04eff94
<stdin>
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
interface IERC20 {
function balanceOf(address) external view returns (uint256);
}
interface IERC165 {
function supportsInterface(bytes4) external view returns (bool);
}
interface IERC721 {
function ownerOf(uint256 id) external view returns (address);
function transferFrom(address from, address to, uint256 id) external;
}
interface IERC1155 {
function balanceOf(address account, uint256 id) external view returns (uint256);
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
}
/// LatticeOTC — a trustless over-the-counter swap between two parties.
///
/// The maker escrows what they give (native coin, ERC20s, ERC721s, ERC1155s — up to MAX_ASSETS) and
/// names what they want for it, an expiry and optionally the one address that may take it. A taker
/// fills it in one transaction: what the maker wants goes from the taker straight to the maker and
/// the escrow goes to the taker — both legs or neither. Until then the maker may cancel; from the
/// expiry on, anyone may send the escrow back to the maker (and only to the maker).
///
/// A fill names the terms it agrees to (`terms`, the hash of maker, taker, expiry and both asset
/// lists as recorded), so a fill can never land on a different offer than the one the taker read —
/// offer ids are sequential and a pending `create` can be reordered.
///
/// A fill pays a fee of FEE_BPS (0.5%) on the native coin it moves, to `feeTo`: whoever receives the
/// coin gets the rest (the maker of what they wanted, or the taker of an escrowed amount); the taker
/// always sends exactly what the offer names. The chain's wrapped coin (WETH, WBNB, WHYPE, Arc's USDC
/// ERC-20 — isWrappedNative, fixed per chain id in this code) is charged the same way, so wrapping the
/// coin doesn't skip the fee. Other ERC20s and NFTs move in full. Cancel and reclaim are free. Fees
/// are only ever credited (withdrawNative / withdrawToken collect them), so no call to the fee address
/// sits inside a fill. `feeTo` (set at deployment; address(0): no fee) may hand its role to another
/// address, which must accept it, or give it up for good — and nothing else: it can't touch an offer.
///
/// The open offers are listed on chain (openCount / openOffers): one is added when it's created and
/// taken off when it's filled, cancelled or reclaimed. One past its expiry stays listed until it's
/// reclaimed — a reader filters those by `expiry`.
///
/// No owner, no upgrade: the same code at the same address on every chain for the same `feeTo`
/// (CREATE2 through the deterministic deployment proxy), and nobody but the two parties of an offer
/// can ever move what it holds.
///
/// Not supported: rebasing tokens and tokens that charge a fee *on top of* the amount moved (one
/// balance backs every offer of a token, so a token whose balances shrink on their own can leave the
/// last offer short), and partial fills. Fee-on-transfer tokens that deduct from the amount are fine:
/// the escrow records what actually arrived.
contract LatticeOTC {
enum Kind { NATIVE, ERC20, ERC721, ERC1155 }
enum Status { NONE, OPEN, FILLED, CANCELLED, RECLAIMED }
struct Asset {
Kind kind;
address token; // address(0) for the native coin
uint256 id; // ERC721 / ERC1155 token id, else 0
uint256 amount; // ERC20 / ERC1155 / native amount; 1 for an ERC721
}
struct Offer {
address maker;
address taker; // address(0): anyone may fill
uint64 expiry; // fill before, reclaim from
Status status;
bytes32 terms; // hashTerms(maker, taker, expiry, give, want) — what a fill must agree to
Asset[] give; // held here (amounts as actually received)
Asset[] want; // sent by the taker to the maker on fill
}
uint256 public constant MAX_ASSETS = 16; // per side: bounds every loop's gas
uint256 public constant FEE_BPS = 50; // 0.5% of the native coin a fill moves
uint256 public nextId = 1;
mapping(uint256 => Offer) private _offers;
mapping(address => uint256) public nativeOwed; // native coin a recipient's contract refused
mapping(address => mapping(address => uint256)) public tokenOwed; // wrapped-coin fees credited
address public feeTo; // where fees go; address(0): no fee
address public pendingFeeTo; // offered the role, has not accepted yet
uint256[] private _open; // the open offers' ids (in no particular order)
mapping(uint256 => uint256) private _openAt; // id -> its index in _open + 1 (0: not listed)
uint256 private _lock = 1;
event Created(uint256 indexed id, address indexed maker, address indexed taker, uint64 expiry, bytes32 terms);
event Filled(uint256 indexed id, address indexed taker);
event Closed(uint256 indexed id, Status status); // CANCELLED or RECLAIMED: escrow back to maker
event FeePaid(uint256 indexed id, address indexed to, uint256 amount);
event FeePaidToken(uint256 indexed id, address indexed to, address indexed token, uint256 amount);
event FeeToSet(address indexed to);
event FeeToOffered(address indexed to);
event Credited(address indexed to, uint256 amount); // a native push refused, kept for withdrawNative
error BadAsset(uint256 index);
error BadOffer();
error BadTerms();
error WrongValue();
error NotOpen();
error Expired();
error NotExpired();
error NotTaker();
error NotMaker();
error ShortDelivery(uint256 index);
error TransferFailed();
error Reentrancy();
error NotFeeTo();
constructor(address feeTo_) {
feeTo = feeTo_;
emit FeeToSet(feeTo_);
}
modifier nonReentrant() {
if (_lock != 1) revert Reentrancy();
_lock = 2;
_;
_lock = 1;
}
// ------------------------------------------------------------------ maker
/// Escrow `give` (pulled from the caller, who has approved this contract; the native part as
/// msg.value) and offer it for `want` until `expiry`, to `taker` only (or anyone if 0).
function create(Asset[] calldata give, Asset[] calldata want, address taker, uint64 expiry)
external payable nonReentrant returns (uint256 id)
{
if (give.length == 0 || want.length == 0 || give.length > MAX_ASSETS || want.length > MAX_ASSETS
|| expiry <= block.timestamp || taker == msg.sender) revert BadOffer();
// A maker that is a contract (incl. an EIP-7702 delegated account) must take ERC1155 back
// (and in): safeTransferFrom always calls the recipient, so one that can't would leave its
// escrow unreturnable.
if (msg.sender.code.length > 0 && (_has1155(give) || _has1155(want))
&& !_supports(msg.sender, 0x4e2312e0)) revert BadOffer();
id = nextId++;
Offer storage o = _offers[id];
(o.maker, o.taker, o.expiry) = (msg.sender, taker, expiry);
// `held` is `give` with the amounts that actually arrived; it is what the escrow owes.
Asset[] memory held = new Asset[](give.length);
uint256 native;
for (uint256 i; i < give.length; ++i) {
Asset calldata a = give[i];
_check(a, i);
if (a.kind == Kind.NATIVE) {
native += a.amount;
held[i] = a;
} else {
held[i] = Asset(a.kind, a.token, a.id, _pullIn(a, msg.sender, i));
}
o.give.push(held[i]);
}
if (msg.value != native) revert WrongValue();
for (uint256 i; i < want.length; ++i) {
_check(want[i], i);
o.want.push(want[i]);
}
bytes32 terms = hashTerms(msg.sender, taker, expiry, held, want);
o.terms = terms;
o.status = Status.OPEN; // last: nothing observed during the pulls above looks like an open offer
_open.push(id);
_openAt[id] = _open.length;
emit Created(id, msg.sender, taker, expiry, terms);
}
/// The maker withdraws an open offer (any time: a taker has committed nothing until the fill,
/// which is atomic). For a firm offer that can't be pulled before its expiry, drop this.
function cancel(uint256 id) external nonReentrant {
Offer storage o = _offers[id];
if (o.status != Status.OPEN) revert NotOpen();
if (msg.sender != o.maker) revert NotMaker();
_close(id, o, Status.CANCELLED);
}
/// After the expiry anyone may send the escrow back to the maker (only ever to the maker).
function reclaim(uint256 id) external nonReentrant {
Offer storage o = _offers[id];
if (o.status != Status.OPEN) revert NotOpen();
if (block.timestamp < o.expiry) revert NotExpired();
_close(id, o, Status.RECLAIMED);
}
// ------------------------------------------------------------------ taker
/// Send the maker everything they want (pulled from the caller; the native part as msg.value)
/// and receive the escrow — all or nothing, in this one transaction. `terms` is the offer's
/// terms hash as read (offer(id).terms): the fill reverts if the offer at `id` is any other.
function fill(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) revert Expired();
if ((o.taker != address(0) && msg.sender != o.taker) || msg.sender == o.maker) revert NotTaker();
o.status = Status.FILLED; // effects before any external call
_unlist(id);
address maker = o.maker;
address to = feeTo;
uint256 native;
for (uint256 i; i < o.want.length; ++i) if (o.want[i].kind == Kind.NATIVE) native += o.want[i].amount;
if (msg.value != native) revert WrongValue();
uint256 fees;
for (uint256 i; i < o.want.length; ++i) {
Asset memory a = o.want[i];
if (a.kind == Kind.NATIVE) {
uint256 f = _fee(a.amount, to);
fees += f;
_sendNative(maker, a.amount - f);
} else if (a.kind == Kind.ERC20 && to != address(0) && isWrappedNative(a.token)) {
// The wrapped coin: the maker gets the rest, the fee comes here and is credited.
uint256 f = _fee(a.amount, to);
_deliver(Asset(Kind.ERC20, a.token, 0, a.amount - f), msg.sender, maker, i);
if (f != 0) {
uint256 before = IERC20(a.token).balanceOf(address(this));
_erc20Call(a.token, abi.encodeWithSelector(0x23b872dd, msg.sender, address(this), f));
if (IERC20(a.token).balanceOf(address(this)) - before < f) revert ShortDelivery(i);
_creditToken(id, to, a.token, f);
}
} else {
_deliver(a, msg.sender, maker, i);
}
}
for (uint256 i; i < o.give.length; ++i) {
Asset memory a = o.give[i];
if (a.kind == Kind.NATIVE) {
uint256 f = _fee(a.amount, to);
fees += f;
_sendNative(msg.sender, a.amount - f);
} else if (a.kind == Kind.ERC20 && to != address(0) && isWrappedNative(a.token)) {
// Escrowed wrapped coin: the taker gets the rest, the fee stays here, credited.
uint256 f = _fee(a.amount, to);
_payOut(Asset(Kind.ERC20, a.token, 0, a.amount - f), msg.sender);
if (f != 0) _creditToken(id, to, a.token, f);
} else {
_payOut(a, msg.sender);
}
}
if (fees != 0) {
nativeOwed[to] += fees; // credited, never pushed: the fee address can't slow a fill
emit FeePaid(id, to, fees);
}
emit Filled(id, msg.sender);
}
/// The fee address offers its role to `to`, who takes it with acceptFeeTo (so a mistyped address
/// loses nothing), or gives it up for good with address(0): no fee from then on. Nothing else.
function setFeeTo(address to) external {
if (msg.sender != feeTo) revert NotFeeTo();
if (to == address(0)) {
delete pendingFeeTo;
feeTo = address(0);
emit FeeToSet(address(0));
} else {
pendingFeeTo = to;
emit FeeToOffered(to);
}
}
function acceptFeeTo() external {
if (msg.sender != pendingFeeTo) revert NotFeeTo();
delete pendingFeeTo;
feeTo = msg.sender;
emit FeeToSet(msg.sender);
}
/// Native coin whose push was refused (a contract recipient without a payable receive).
/// Wrapped-coin fees credited to the caller (the fee address, or one it handed the role on from).
function withdrawToken(address token) external nonReentrant {
uint256 v = tokenOwed[msg.sender][token];
tokenOwed[msg.sender][token] = 0;
if (v != 0) _erc20Call(token, abi.encodeWithSelector(0xa9059cbb, msg.sender, v));
}
/// The chain's wrapped native coin, charged like the coin itself (fixed per chain id here, so one
/// code serves every chain and nobody can change what's charged): WETH on Ethereum, Base, Ink,
/// Robinhood Chain and Arbitrum; WBNB on BNB Chain; Arc's USDC ERC-20 (its gas coin's own face); both WHYPEs on
/// Elysium. Any other chain: none.
function isWrappedNative(address token) public view returns (bool) {
uint256 c = block.chainid;
if (c == 1) return token == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
if (c == 8453 || c == 57073) return token == 0x4200000000000000000000000000000000000006;
if (c == 56) return token == 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c;
if (c == 4663) return token == 0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73;
if (c == 42161) return token == 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1;
if (c == 5042) return token == 0x3600000000000000000000000000000000000000;
if (c == 99901) {
return token == 0xbA876237B0F021A6c6D852d6c26E107997cC5E81
|| token == 0x5ab377328592C03b5E7aDB09254aDb043F91fA11;
}
return false;
}
function withdrawNative() external nonReentrant {
uint256 v = nativeOwed[msg.sender];
nativeOwed[msg.sender] = 0;
(bool ok, ) = msg.sender.call{value: v}("");
if (!ok) revert TransferFailed();
}
// ------------------------------------------------------------------ reads
function offer(uint256 id) external view returns (Offer memory) {
return _offers[id];
}
/// How many offers are open (expired ones not yet reclaimed included).
function openCount() external view returns (uint256) {
return _open.length;
}
/// Up to `count` open offers from position `start` of the list, with their ids. The order is the
/// list's (a closed offer's place is taken by the last one), not the ids'.
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 fill agrees to. `give` must be the recorded list (offer(id).give), whose amounts
/// may be below what the maker asked to escrow for a fee-on-transfer token.
function hashTerms(address maker, address taker, uint64 expiry, Asset[] memory give, Asset[] memory want)
public pure returns (bytes32)
{
return keccak256(abi.encode(maker, taker, expiry, give, want));
}
// ------------------------------------------------------------------ internals
function _close(uint256 id, Offer storage o, Status s) private {
o.status = s;
_unlist(id);
for (uint256 i; i < o.give.length; ++i) _payOut(o.give[i], o.maker);
emit Closed(id, s);
}
/// Off the open list: the last one takes its place.
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];
}
function _creditToken(uint256 id, address to, address token, uint256 f) private {
tokenOwed[to][token] += f; // credited, never pushed: the fee address can't slow a fill
emit FeePaidToken(id, to, token, f);
}
function _fee(uint256 amount, address to) private pure returns (uint256) {
return to == address(0) ? 0 : amount * FEE_BPS / 10_000;
}
/// An asset is what it says it is. An NFT contract must claim its interface, and an "ERC20" must
/// not claim an NFT interface: ERC20 and ERC721 share the transferFrom selector, so an NFT listed
/// as an ERC20 of `amount` would move token id `amount` — from a taker who had only approved the
/// collection, under the guise of a fungible amount — and could never be paid back out.
function _check(Asset calldata a, uint256 i) private view {
if (a.kind == Kind.NATIVE) {
if (a.token != address(0) || a.id != 0 || a.amount == 0) revert BadAsset(i);
return;
}
if (a.token.code.length == 0) revert BadAsset(i);
if (a.kind == Kind.ERC20) {
if (a.id != 0 || a.amount == 0 || _supports(a.token, 0x80ac58cd) || _supports(a.token, 0xd9b67a26))
revert BadAsset(i);
} else if (a.kind == Kind.ERC721) {
if (a.amount != 1 || !_supports(a.token, 0x80ac58cd)) revert BadAsset(i);
} else if (a.amount == 0 || !_supports(a.token, 0xd9b67a26)) {
revert BadAsset(i);
}
}
function _has1155(Asset[] calldata list) private pure returns (bool) {
for (uint256 i; i < list.length; ++i) if (list[i].kind == Kind.ERC1155) return true;
return false;
}
function _supports(address t, bytes4 iface) private view returns (bool) {
// Low-level so that a target that returns malformed data reads as "no" instead of reverting
// (abi.decode as bool would revert on a word other than 0 or 1).
(bool ok, bytes memory ret) = t.staticcall(abi.encodeWithSelector(IERC165.supportsInterface.selector, iface));
return ok && ret.length == 32 && uint256(bytes32(ret)) == 1;
}
/// Maker → escrow. Only ever from msg.sender: never an arbitrary `from` (an approval-drain hole).
/// Returns what actually arrived — the escrow records that, never the amount asked for, so no
/// offer can be backed by another offer's balance of the same token.
function _pullIn(Asset calldata a, address from, uint256 i) private returns (uint256 got) {
if (a.kind == Kind.ERC20) {
uint256 before = IERC20(a.token).balanceOf(address(this));
_erc20Call(a.token, abi.encodeWithSelector(0x23b872dd, from, address(this), a.amount));
got = IERC20(a.token).balanceOf(address(this)) - before;
} else if (a.kind == Kind.ERC721) {
IERC721(a.token).transferFrom(from, address(this), a.id);
// Like the balance checks for fungibles: the escrow records only what it verifiably holds.
if (IERC721(a.token).ownerOf(a.id) != address(this)) revert ShortDelivery(i);
got = 1;
} else {
uint256 before = IERC1155(a.token).balanceOf(address(this), a.id);
IERC1155(a.token).safeTransferFrom(from, address(this), a.id, a.amount, "");
got = IERC1155(a.token).balanceOf(address(this), a.id) - before;
}
if (got == 0) revert ShortDelivery(i);
}
/// Taker → maker, directly. An ERC20 must arrive in full (a fee-on-transfer token is the
/// taker's to cover, or the fill reverts).
function _deliver(Asset memory a, address from, address to, uint256 i) private {
if (a.kind == Kind.ERC20) {
uint256 before = IERC20(a.token).balanceOf(to);
_erc20Call(a.token, abi.encodeWithSelector(0x23b872dd, from, to, a.amount));
if (IERC20(a.token).balanceOf(to) - before < a.amount) revert ShortDelivery(i);
} else if (a.kind == Kind.ERC721) {
IERC721(a.token).transferFrom(from, to, a.id);
if (IERC721(a.token).ownerOf(a.id) != to) revert ShortDelivery(i);
} else {
IERC1155(a.token).safeTransferFrom(from, to, a.id, a.amount, "");
}
}
/// Escrow → `to` (the taker on a fill, the maker on cancel / reclaim).
function _payOut(Asset memory a, address to) private {
if (a.kind == Kind.NATIVE) {
_sendNative(to, a.amount);
} else if (a.kind == Kind.ERC20) {
_erc20Call(a.token, abi.encodeWithSelector(0xa9059cbb, to, a.amount));
} else if (a.kind == Kind.ERC721) {
// Plain transferFrom: no receiver callback, so a recipient can't block a payout.
IERC721(a.token).transferFrom(address(this), to, a.id);
} else {
IERC1155(a.token).safeTransferFrom(address(this), to, a.id, a.amount, "");
}
}
/// Pushed; a recipient that refuses it can pull it later (withdrawNative) instead of blocking.
function _sendNative(address to, uint256 v) private {
(bool ok, ) = to.call{value: v}("");
if (!ok) {
nativeOwed[to] += v;
emit Credited(to, v);
}
}
/// SafeERC20: tokens that return nothing (USDT), ones that return false, and ones that return
/// something that isn't a bool all handled.
function _erc20Call(address token, bytes memory data) private {
(bool ok, bytes memory ret) = token.call(data);
if (!ok || (ret.length != 0 && (ret.length < 32 || !abi.decode(ret, (bool))))) revert TransferFailed();
}
// The escrow can hold NFTs sent with safeTransferFrom.
function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
return this.onERC721Received.selector;
}
function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata)
external pure returns (bytes4)
{
return this.onERC1155BatchReceived.selector;
}
function supportsInterface(bytes4 i) external pure returns (bool) {
return i == 0x01ffc9a7 || i == 0x4e2312e0; // ERC165, ERC1155Receiver
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 300,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.