Verified contractPartialMIT
Lattice
Address0x1f2bb5ecec1066f298d1fbea4240432f4fe8ed63
- Balance
0 ETH
- Transactions
4
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,392,241
- Creation transaction
- 0x8945564d78…0819b9fac1
2 files
- lattice/src/Lattice.solmain16.1 KB
- lattice/src/LatticeShapes.sol4.66 KB
lattice/src/Lattice.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
// web: https://latticepq.xyz x: https://x.com/lattice_quantum
//
// LATTICE . CRYSTAL REPORT . plane (1 0 0): the coin and its lattice accounts.
//
// Composition: 1,000,000,000 LATTICE, all minted once to the hook, which puts every unit in the pool at open().
// Two phases: an ordinary ERC-20 balance, held by an Ethereum key; and a lattice account, held by an ML-DSA-65 key
// (FIPS 204). A lattice account's id is keccak256 of its public key; its coins sit in this contract and
// move only by an order that key signed, verified on chain (LatticeKeys.check, about 3.4M gas). Anyone may
// relay a signed order and pay its gas; the order can tip, in LATTICE, whoever makes it run (the relayer,
// or for a queued order whoever executes it). A tip leaves the account only when the order runs, and only
// outside a hold, like a withdrawal.
// Orders: 1 WITHDRAW to an address 2 SEND to another lattice id 3 SELL through the Door, ETH to an address
// 4 CLAIM the account's ETH 5 GUARD: set a delay, a recovery key and a haven 6 CANCEL a queued order
// 7 SWEEP everything to the haven (recovery key only)
// Guard: with a delay set, every owner order but CANCEL waits in a queue (16 at most) for the delay, after which
// anyone may execute it until the order's own deadline, which must reach past the delay. The recovery key
// (another lattice id) may CANCEL at once, or SWEEP the whole account, coins and ETH, at once, but only to
// the haven: a lattice id the account's own key named in its GUARD order. It takes no tips and has its own
// nonce, so a stolen account key cannot spend the recovery's signed order by moving the nonce first. It can
// do nothing else: a stolen recovery key can at worst move everything to the owner's own haven.
// A guarded account cannot SELL: a queued sale would carry a minOut signed days before anyone executes it,
// and the executor could sandwich it down to that. Withdraw (queued) and sell from the address instead.
// Ids: any bytes32 can receive coins; an id that is not the keccak256 of a real ML-DSA-65 key can never move
// them again. Check the id before you lock to it.
// Yield: the hook pays 0.5% of all pool volume, in ETH, over the coins held in lattice accounts, by the weight
// they hold at that moment; signed full-precision corrections, so a later change of balance never
// rewrites ETH already earned. While fewer than 1,000 coins are in lattice accounts the hook pays it all to
// the owner (a smaller total would let a few wei collect the stream and overflow the accumulator).
// Hold: a deposit worth at least a tenth of the receiving account's new balance freezes that account's
// WITHDRAW, SELL, SEND and tips for an hour, so coins cannot be locked just before a large swap and taken out after
// it. A smaller deposit freezes nothing: holding someone's account frozen costs a tenth of its balance,
// which becomes theirs.
// Limits: the signature is post-quantum; Ethereum itself is not. The ETH that pays a relayer's gas, Ethereum's
// consensus and the pool's owner key are classical. A lattice account protects the coins in it, nothing
// more. An ML-DSA key that is lost cannot be recovered without a recovery key set beforehand.
import {Order, ILatticeKeys, ILatticeDoor} from "./LatticeShapes.sol";
contract Lattice {
string public constant name = "Lattice";
string public constant symbol = "LATTICE";
uint8 public constant decimals = 18;
uint256 public constant totalSupply = 1_000_000_000 ether;
bytes32 public constant ORDER_TAG = keccak256("LATTICE_ORDER_V1");
uint256 public constant HOLD = 1 hours;
uint256 public constant MAX_DELAY = 30 days;
uint256 public constant MAX_QUEUED = 16;
/// @dev Below this many coins in lattice accounts the hook pays the holders' half to the owner: a tiny total would
/// let one wei collect the stream and overflow the per-coin accumulator.
uint256 public constant MIN_EARNING = 1_000 ether;
uint256 internal constant MAG = 1 << 128;
uint8 public constant WITHDRAW = 1;
uint8 public constant SEND = 2;
uint8 public constant SELL = 3;
uint8 public constant CLAIM = 4;
uint8 public constant GUARD = 5;
uint8 public constant CANCEL = 6;
uint8 public constant SWEEP = 7;
uint8 public constant BY_KEY = 0;
uint8 public constant BY_RECOVERY = 1;
address public immutable hook;
address public immutable keys;
address public door;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
struct Account {
uint128 balance;
uint64 nonce;
uint64 heldUntil;
uint32 delay;
uint8 queued;
uint32 generation;
uint64 recoveryNonce;
bytes32 recovery;
bytes32 haven;
int256 corr;
uint256 paid;
uint256 extra;
}
/// @dev A SWEEP bumps the account's generation, which retires every order queued before it at once.
struct Queued {
Order order;
uint64 unlockAt;
uint32 generation;
bool live;
}
mapping(bytes32 => Account) public accounts;
mapping(bytes32 => Queued[]) internal _pending;
uint256 public latticeTotal;
uint256 public perCoin;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Locked(bytes32 indexed id, address indexed from, uint256 amount, uint64 heldUntil);
event Ordered(bytes32 indexed id, uint8 role, uint8 kind, uint64 nonce, bytes32 target, uint256 amount, address relayer);
event Queue(bytes32 indexed id, uint256 index, uint64 unlockAt);
event Executed(bytes32 indexed id, uint256 index);
event Cancelled(bytes32 indexed id, uint256 index);
event Swept(bytes32 indexed from, bytes32 indexed to, uint256 coins, uint256 eth);
event YieldPoured(uint256 amount, uint256 latticeTotal);
event Claimed(bytes32 indexed id, address indexed to, uint256 amount);
error OnlyHook();
error DoorBound();
error Expired();
error StaleNonce();
error BadSignature();
error NoRecovery();
error NotAllowed();
error Held();
error Short();
error QueueFull();
error NothingQueued();
error Locked_();
error BadOrder();
error SendFailed();
error Reentry();
constructor(address keys_) {
hook = msg.sender;
keys = keys_;
balanceOf[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
modifier once() {
bool busy;
assembly {
busy := tload(0x1a77)
}
if (busy) revert Reentry();
assembly {
tstore(0x1a77, 1)
}
_;
assembly {
tstore(0x1a77, 0)
}
}
/// @notice The hook, once, at open(): the Door that SELL orders go through.
function bindDoor(address door_) external {
if (msg.sender != hook) revert OnlyHook();
if (door != address(0)) revert DoorBound();
door = door_;
}
// ---- ERC-20
function transfer(address to, uint256 amount) external returns (bool) {
_move(msg.sender, to, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) external returns (bool) {
uint256 a = allowance[from][msg.sender];
if (a != type(uint256).max) allowance[from][msg.sender] = a - amount;
_move(from, to, amount);
return true;
}
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function _move(address from, address to, uint256 amount) internal {
balanceOf[from] -= amount;
balanceOf[to] += amount;
emit Transfer(from, to, amount);
}
// ---- into a lattice account
/// @notice Anyone may put their own coins into any lattice account. The id need not have a key written yet.
function lock(bytes32 id, uint256 amount) external once {
if (amount == 0) revert Short();
_move(msg.sender, address(this), amount);
_credit(id, amount);
emit Locked(id, msg.sender, amount, accounts[id].heldUntil);
}
function _rebalance(bytes32 id, uint256 nb) internal {
Account storage a = accounts[id];
uint256 ob = a.balance;
if (nb > ob) {
latticeTotal += nb - ob;
a.corr -= int256(perCoin * (nb - ob));
} else if (nb < ob) {
latticeTotal -= ob - nb;
a.corr += int256(perCoin * (ob - nb));
}
a.balance = uint128(nb);
}
function _credit(bytes32 id, uint256 amount) internal {
uint256 nb = uint256(accounts[id].balance) + amount;
_rebalance(id, nb);
if (amount * 10 >= nb) accounts[id].heldUntil = uint64(block.timestamp + HOLD);
}
function _debit(bytes32 id, uint256 amount) internal {
uint256 b = accounts[id].balance;
if (amount > b) revert Short();
_rebalance(id, b - amount);
}
// ---- the yield
/// @notice The hook's 0.5% of volume, spread over the coins in lattice accounts now. The hook never rains on none.
function pourYield() external payable {
if (msg.sender != hook || latticeTotal < MIN_EARNING) revert OnlyHook();
perCoin += (msg.value * MAG) / latticeTotal;
emit YieldPoured(msg.value, latticeTotal);
}
function claimable(bytes32 id) public view returns (uint256) {
Account storage a = accounts[id];
int256 g = int256(perCoin * a.balance) + a.corr;
uint256 earned = (g > 0 ? uint256(g) / MAG : 0) + a.extra;
return earned > a.paid ? earned - a.paid : 0;
}
// ---- orders
/// @notice The exact bytes an order's key signs (FIPS 204 ML-DSA-65, context "LATTICE").
function message(bytes32 id, uint8 role, Order calldata o) public view returns (bytes memory) {
return abi.encode(ORDER_TAG, block.chainid, address(this), id, role, o);
}
/// @notice Relay an order signed by the account's key (role 0) or its recovery key (role 1).
function order(bytes32 id, uint8 role, Order calldata o, bytes calldata sig) external once {
Account storage a = accounts[id];
if (block.timestamp > o.deadline) revert Expired();
if (o.kind == 0 || o.kind > SWEEP) revert BadOrder();
bytes32 signer = id;
if (role == BY_RECOVERY) {
signer = a.recovery;
if (signer == bytes32(0)) revert NoRecovery();
if ((o.kind != CANCEL && o.kind != SWEEP) || o.tip != 0) revert NotAllowed();
if (o.nonce != a.recoveryNonce) revert StaleNonce();
} else {
if (role != BY_KEY || o.kind == SWEEP || (o.kind == CANCEL && o.tip != 0)) revert NotAllowed();
if (o.nonce != a.nonce) revert StaleNonce();
}
if (!ILatticeKeys(keys).check(signer, message(id, role, o), sig)) revert BadSignature();
if (role == BY_RECOVERY) a.recoveryNonce += 1;
else a.nonce += 1;
emit Ordered(id, role, o.kind, o.nonce, o.target, o.amount, msg.sender);
if (o.kind == CANCEL) {
_drop(id, o.amount);
} else if (o.kind == SWEEP) {
_evacuate(id);
} else if (a.delay != 0) {
if (o.kind == SELL) revert NotAllowed();
if (a.queued >= MAX_QUEUED) revert QueueFull();
uint64 at = uint64(block.timestamp + a.delay);
// the signer chose how long the order may wait to be executed; it must outlast the delay
if (o.deadline < at) revert Expired();
a.queued += 1;
_pending[id].push(Queued(o, at, a.generation, true));
emit Queue(id, _pending[id].length - 1, at);
} else {
_run(id, o, msg.sender);
}
}
/// @notice Anyone may execute a queued order between the end of its delay and its deadline; the tip is theirs.
function execute(bytes32 id, uint256 index) external once {
Queued storage q = _pending[id][index];
if (!q.live || q.generation != accounts[id].generation) revert NothingQueued();
if (block.timestamp < q.unlockAt) revert Locked_();
if (block.timestamp > q.order.deadline) revert Expired();
q.live = false;
accounts[id].queued -= 1;
_run(id, q.order, msg.sender);
emit Executed(id, index);
}
function _drop(bytes32 id, uint256 index) internal {
Queued storage q = _pending[id][index];
if (!q.live || q.generation != accounts[id].generation) revert NothingQueued();
q.live = false;
accounts[id].queued -= 1;
emit Cancelled(id, index);
}
function _evacuate(bytes32 id) internal {
Account storage a = accounts[id];
bytes32 to = a.haven;
if (to == id || to == bytes32(0)) revert BadOrder();
uint256 coins = a.balance;
uint256 eth = claimable(id);
a.paid += eth;
accounts[to].extra += eth;
a.generation += 1;
a.queued = 0;
_rebalance(id, 0);
_rebalance(to, uint256(accounts[to].balance) + coins);
emit Swept(id, to, coins, eth);
}
function _run(bytes32 id, Order memory o, address payee) internal {
Account storage a = accounts[id];
uint8 k = o.kind;
if (o.tip != 0) {
// a tip leaves the lattice like a withdrawal: never inside a hold, only as the order runs
if (block.timestamp < a.heldUntil) revert Held();
_debit(id, o.tip);
_move(address(this), payee, o.tip);
}
if (k == WITHDRAW || k == SELL) {
if (block.timestamp < a.heldUntil) revert Held();
_debit(id, o.amount);
address to = address(uint160(uint256(o.target)));
if (to == address(0)) revert BadOrder();
if (k == WITHDRAW) {
_move(address(this), to, o.amount);
} else {
_move(address(this), door, o.amount);
ILatticeDoor(door).sellForOrder(o.amount, o.minOut, to);
}
} else if (k == SEND) {
if (block.timestamp < a.heldUntil) revert Held();
if (o.target == id) revert BadOrder();
_debit(id, o.amount);
_credit(o.target, o.amount);
} else if (k == CLAIM) {
uint256 amount = claimable(id);
a.paid += amount;
address to = address(uint160(uint256(o.target)));
if (to == address(0)) revert BadOrder();
(bool ok,) = to.call{value: amount}("");
if (!ok) revert SendFailed();
emit Claimed(id, to, amount);
} else {
// GUARD: target is the haven, the only place the recovery key can SWEEP to
if (o.delay > MAX_DELAY || o.recovery == id || o.target == id) revert BadOrder();
if (o.recovery != bytes32(0) && o.target == bytes32(0)) revert BadOrder();
a.delay = o.delay;
a.recovery = o.recovery;
a.haven = o.target;
}
}
// ---- views
function queued(bytes32 id, uint256 index) external view returns (Order memory o, uint64 unlockAt, bool live) {
Queued storage q = _pending[id][index];
return (q.order, q.unlockAt, q.live && q.generation == accounts[id].generation);
}
function queueLength(bytes32 id) external view returns (uint256) {
return _pending[id].length;
}
}
lattice/src/LatticeShapes.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
// web: https://latticepq.xyz x: https://x.com/lattice_quantum
//
// LATTICE . CRYSTAL REPORT . plane (0 0 1): the ground the crystal grows on.
//
// Sample: Ethereum mainnet. Uniswap v4 PoolManager and PositionManager, Permit2, nothing else from outside.
// Habit: every outside address is a constant here; no constructor argument can point the crystal elsewhere.
// The verifier is not a constant: LatticeKeys is told it once at deployment, and the launch desk reads it back.
struct PoolKey {
address currency0;
address currency1;
uint24 fee;
int24 tickSpacing;
address hooks;
}
struct SwapParams {
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
}
/// @dev One signed instruction for a lattice account. Which fields count depends on `kind` (see Lattice.sol).
struct Order {
uint8 kind;
uint64 nonce;
uint64 deadline;
bytes32 target; // an address in the low 160 bits, or a lattice id
uint256 amount;
uint256 minOut;
uint256 tip; // LATTICE to whoever relays the order
uint32 delay;
bytes32 recovery;
}
interface IPoolManager {
function unlock(bytes calldata data) external returns (bytes memory);
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData) external returns (int256);
function settle() external payable returns (uint256);
function sync(address currency) external;
function take(address currency, address to, uint256 amount) external;
function extsload(bytes32 slot) external view returns (bytes32);
}
interface IPositionManager {
function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
function nextTokenId() external view returns (uint256);
}
interface IPermit2 {
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
}
/// @dev MLDSA65.yul: FIPS 204 ML-DSA-65 verification against a key expanded into three code contracts.
interface IMLDSA65 {
function verifyStored(address part0, address part1, address part2, bytes calldata message, bytes calldata context, bytes calldata sig)
external
view
returns (bool);
function expandPart(bytes calldata pk, uint256 part) external view returns (bytes memory);
}
interface ILatticeKeys {
function check(bytes32 id, bytes calldata message, bytes calldata sig) external view returns (bool);
}
interface ILatticeToken {
function pourYield() external payable;
function latticeTotal() external view returns (uint256);
function lock(bytes32 id, uint256 amount) external;
function bindDoor(address door) external;
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address a) external view returns (uint256);
}
interface ILatticeDoor {
function sellForOrder(uint256 amount, uint256 minOut, address to) external returns (uint256);
}
library Mainnet {
address internal constant POOL_MANAGER = 0x000000000004444c5dc75cB358380D2e3dE08A90;
address internal constant POSITION_MANAGER = 0xbD216513d74C8cf14cf4747E6AaA6420FF64ee9e;
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
}
/// @dev The one pool: ETH / LATTICE, LP fee 0 (the hook's 1% is the only fee), tick spacing 200.
library Cell {
uint24 internal constant LP_FEE = 0;
int24 internal constant SPACING = 200;
int24 internal constant TICK_BASE = -887200;
int24 internal constant TICK_TOP = 207200; // 1.0001^207200 LATTICE per ETH: the whole supply at a 1.0043 ETH FDV
uint160 internal constant SQRT_BASE = 4310618292; // TickMath at -887200, read off a chain
uint160 internal constant SQRT_TOP = 2500031419217008302293562112940196; // TickMath at 207200, read off a chain
function key(address token, address hook) internal pure returns (PoolKey memory) {
return PoolKey(address(0), token, LP_FEE, SPACING, hook);
}
/// @dev StateLibrary: pools live at mapping slot 6; slot0's low 160 bits are the sqrt price.
function sqrtPrice(address token, address hook) internal view returns (uint160) {
bytes32 s = keccak256(abi.encodePacked(keccak256(abi.encode(key(token, hook))), uint256(6)));
return uint160(uint256(IPoolManager(Mainnet.POOL_MANAGER).extsload(s)));
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none"
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.