Verified contractExactMIT
LatticeOTC
Address0x7a473b91d3f05aff74394dfab4c4cef815bf75c8
- 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,361,844
- Creation transaction
- 0xbc9e584cd8…7199bcada2
<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 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.
///
/// No owner, no upgrade, no fee, no constructor arguments: the same code at the same address on every
/// chain (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 nextId = 1;
mapping(uint256 => Offer) private _offers;
mapping(address => uint256) public nativeOwed; // native coin a recipient's contract refused
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
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();
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
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
address maker = o.maker;
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();
for (uint256 i; i < o.want.length; ++i) {
Asset memory a = o.want[i];
if (a.kind == Kind.NATIVE) _sendNative(maker, a.amount);
else _deliver(a, msg.sender, maker, i);
}
for (uint256 i; i < o.give.length; ++i) _payOut(o.give[i], msg.sender);
emit Filled(id, msg.sender);
}
/// Native coin whose push was refused (a contract recipient without a payable receive).
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];
}
/// 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;
for (uint256 i; i < o.give.length; ++i) _payOut(o.give[i], o.maker);
emit Closed(id, s);
}
/// 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);
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);
} 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;
}
/// 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.