// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {SystemInit, Beacon, IERC20Min, ISlabMirror} from "./System.sol"; /// Genesis contract at 0x..b004. Native card machine: pools of SlabMirror slabs, pulls paid in BridgedDollar. /// Weight of a slab = 1e36 / priceUsd18, so expensive cards come out less often. /// Money rules: /// - pull price = EV * (10000 + edgeBps) / 10000, EV = sum(w_i * p_i) / sum(w_i) /// - the EV part stays in the pool balance, the edge part goes to block.coinbase /// - the depositor of the pulled slab is credited its priceOf, paid from the pool's free balance /// (balance minus what the pool already owes); the rest is recorded as owed and paid by claim() /// - the machine never pays more than a pool's balance, and pool balances sum to what the machine holds contract CardMachine is SystemInit { uint256 public constant MAX_SLABS = 200; uint256 internal constant WEIGHT_ONE = 1e36; struct Pool { address creator; uint256 balance; // dollars held for this pool uint256 owedTotal; // dollars this pool owes to depositors uint256 pulls; uint256[] slabs; } address public dollar; address public slabs; uint256 public edgeBps; uint256 public sellBackBps; uint256 public sellBackWindow; uint256 public poolCount; // pool ids are 1..poolCount mapping(uint256 => Pool) internal _pools; mapping(uint256 => uint256) public poolOf; // tokenId => poolId while stocked mapping(uint256 => uint256) internal _indexOf; // tokenId => index in pool.slabs mapping(uint256 => address) public depositorOf; // tokenId => depositor while stocked (address(this) = the pool itself) mapping(uint256 => address) public pulledBy; // tokenId => puller (sell back right) mapping(uint256 => uint256) public pulledAt; mapping(uint256 => uint256) public pulledFrom; mapping(uint256 => mapping(address => uint256)) public owedIn; // poolId => depositor => dollars mapping(address => uint256) public owed; // total across pools mapping(address => uint256[]) internal _owedPools; uint256 internal _lock; // 0 unlocked, 1 locked (zero storage in genesis = unlocked) event PoolCreated(uint256 indexed poolId, address indexed creator); event Stocked(uint256 indexed poolId, address indexed depositor, uint256 tokenId); event Unstocked(uint256 indexed poolId, address indexed depositor, uint256 tokenId); event Funded(uint256 indexed poolId, address indexed from, uint256 amount); event Pulled(uint256 indexed poolId, address indexed puller, uint256 tokenId, uint256 pricePaid, uint256 cardValue, bytes32 random); event DepositorPaid(uint256 indexed poolId, address indexed depositor, uint256 tokenId, uint256 paid, uint256 owedAdded); event Claimed(address indexed depositor, uint256 amount); event SoldBack(uint256 indexed poolId, address indexed seller, uint256 tokenId, uint256 paid); error ZeroAddress(); error BadParams(); error NoPool(); error PoolFull(); error NotEnoughSlabs(); error NoPrice(); error PriceTooHigh(uint256 price, uint256 maxPrice); error NotDepositor(); error NotInPool(); error NotPuller(); error WindowClosed(); error PoolCannotPay(); error Reentrant(); error TransferFailed(); error NothingToClaim(); modifier nonReentrant() { if (_lock == 1) revert Reentrant(); _lock = 1; _; _lock = 0; } modifier poolExists(uint256 poolId) { if (poolId == 0 || poolId > poolCount) revert NoPool(); _; } function initialize(address dollar_, address slabs_, uint256 edgeBps_, uint256 sellBackBps_, uint256 sellBackWindow_) external initializer { if (dollar_ == address(0) || slabs_ == address(0)) revert ZeroAddress(); if (edgeBps_ > 10000 || sellBackBps_ > 10000) revert BadParams(); dollar = dollar_; slabs = slabs_; edgeBps = edgeBps_; sellBackBps = sellBackBps_; sellBackWindow = sellBackWindow_; } // ---------------------------------------------------------------- pools function createPool() external whenInitialized returns (uint256 poolId) { poolId = ++poolCount; _pools[poolId].creator = msg.sender; emit PoolCreated(poolId, msg.sender); } function stock(uint256 poolId, uint256 tokenId) external whenInitialized poolExists(poolId) nonReentrant { if (ISlabMirror(slabs).priceOf(tokenId) == 0) revert NoPrice(); _addSlab(poolId, tokenId, msg.sender); emit Stocked(poolId, msg.sender, tokenId); ISlabMirror(slabs).transferFrom(msg.sender, address(this), tokenId); } function unstock(uint256 poolId, uint256 tokenId) external whenInitialized poolExists(poolId) nonReentrant { if (poolOf[tokenId] != poolId) revert NotInPool(); if (depositorOf[tokenId] != msg.sender) revert NotDepositor(); _removeSlab(poolId, tokenId); emit Unstocked(poolId, msg.sender, tokenId); ISlabMirror(slabs).transferFrom(address(this), msg.sender, tokenId); } /// Adds dollars to a pool's balance (liquidity for depositor payouts and sell backs). Anyone. function fund(uint256 poolId, uint256 amount) external whenInitialized poolExists(poolId) nonReentrant { if (amount == 0) revert BadParams(); _pools[poolId].balance += amount; emit Funded(poolId, msg.sender, amount); _pullDollars(msg.sender, amount); } // ---------------------------------------------------------------- pricing /// Expected card value of one pull, in usd18. function expectedValue(uint256 poolId) public view poolExists(poolId) returns (uint256 ev) { (ev,,) = _ev(poolId); } function pullPrice(uint256 poolId) public view poolExists(poolId) returns (uint256) { (uint256 ev,,) = _ev(poolId); return ev * (10000 + edgeBps) / 10000; } function weightOf(uint256 price) public pure returns (uint256) { return price == 0 ? 0 : WEIGHT_ONE / price; } function _ev(uint256 poolId) internal view returns (uint256 ev, uint256 totalWeight, uint256[] memory weights) { uint256[] storage list = _pools[poolId].slabs; uint256 n = list.length; weights = new uint256[](n); uint256 weighted; ISlabMirror s = ISlabMirror(slabs); for (uint256 i; i < n; ++i) { uint256 p = s.priceOf(list[i]); uint256 w = weightOf(p); weights[i] = w; totalWeight += w; weighted += w * p; } if (totalWeight == 0) return (0, 0, weights); ev = weighted / totalWeight; } // ---------------------------------------------------------------- pull function pull(uint256 poolId, uint256 maxPrice) external whenInitialized poolExists(poolId) nonReentrant returns (uint256 tokenId) { uint256 price; uint256 ev; bytes32 random; (tokenId, price, ev, random) = _pick(poolId, maxPrice); Pool storage pool = _pools[poolId]; uint256 cardValue = ISlabMirror(slabs).priceOf(tokenId); address depositor = depositorOf[tokenId]; // effects _removeSlab(poolId, tokenId); pool.pulls += 1; pulledBy[tokenId] = msg.sender; pulledAt[tokenId] = block.timestamp; pulledFrom[tokenId] = poolId; uint256 edge = price - ev; pool.balance += ev; // the EV part stays in the pool if (block.coinbase == address(0)) { pool.balance += edge; // no coinbase to pay: the edge stays in the pool edge = 0; } // a slab whose depositor is the pool itself: its value simply stays in the pool balance uint256 payNow = depositor == address(this) ? 0 : _creditDepositor(poolId, depositor, tokenId, cardValue); emit Pulled(poolId, msg.sender, tokenId, price, cardValue, random); // interactions _pullDollars(msg.sender, price); ISlabMirror(slabs).transferFrom(address(this), msg.sender, tokenId); if (payNow != 0) _sendDollars(depositor, payNow); if (edge != 0) _sendDollars(block.coinbase, edge); } function _pick(uint256 poolId, uint256 maxPrice) internal view returns (uint256 tokenId, uint256 price, uint256 ev, bytes32 random) { Pool storage pool = _pools[poolId]; if (pool.slabs.length < 2) revert NotEnoughSlabs(); uint256 totalWeight; uint256[] memory weights; (ev, totalWeight, weights) = _ev(poolId); if (totalWeight == 0 || ev == 0) revert NoPrice(); price = ev * (10000 + edgeBps) / 10000; if (price > maxPrice) revert PriceTooHigh(price, maxPrice); random = keccak256(abi.encode(Beacon.current(), poolId, pool.pulls, msg.sender)); uint256 r = uint256(random) % totalWeight; uint256 acc; for (uint256 i; i < weights.length; ++i) { acc += weights[i]; if (r < acc) { return (pool.slabs[i], price, ev, random); } } revert NoPrice(); // unreachable: r < totalWeight } function _creditDepositor(uint256 poolId, address depositor, uint256 tokenId, uint256 cardValue) internal returns (uint256 payNow) { Pool storage pool = _pools[poolId]; uint256 free = pool.balance > pool.owedTotal ? pool.balance - pool.owedTotal : 0; payNow = cardValue < free ? cardValue : free; uint256 rest = cardValue - payNow; pool.balance -= payNow; if (rest != 0) { if (owedIn[poolId][depositor] == 0) _owedPools[depositor].push(poolId); owedIn[poolId][depositor] += rest; owed[depositor] += rest; pool.owedTotal += rest; } emit DepositorPaid(poolId, depositor, tokenId, payNow, rest); } /// Pays the caller what pools owe them, as far as each pool's balance reaches. function claim() external whenInitialized nonReentrant returns (uint256 paid) { uint256[] storage list = _owedPools[msg.sender]; uint256 i; while (i < list.length) { uint256 poolId = list[i]; Pool storage pool = _pools[poolId]; uint256 due = owedIn[poolId][msg.sender]; uint256 pay = due < pool.balance ? due : pool.balance; if (pay != 0) { owedIn[poolId][msg.sender] = due - pay; pool.balance -= pay; pool.owedTotal -= pay; paid += pay; } if (owedIn[poolId][msg.sender] == 0) { list[i] = list[list.length - 1]; list.pop(); } else { ++i; } } if (paid == 0) revert NothingToClaim(); owed[msg.sender] -= paid; emit Claimed(msg.sender, paid); _sendDollars(msg.sender, paid); } /// Dollars the caller could claim right now. function claimable(address depositor) external view returns (uint256 amount) { uint256[] storage list = _owedPools[depositor]; for (uint256 i; i < list.length; ++i) { uint256 due = owedIn[list[i]][depositor]; uint256 bal = _pools[list[i]].balance; amount += due < bal ? due : bal; } } /// Returns a pulled slab to its pool within the window for price * sellBackBps / 10000. function sellBack(uint256 poolId, uint256 tokenId) external whenInitialized poolExists(poolId) nonReentrant { if (pulledBy[tokenId] != msg.sender || pulledFrom[tokenId] != poolId) revert NotPuller(); if (block.timestamp > pulledAt[tokenId] + sellBackWindow) revert WindowClosed(); uint256 price = ISlabMirror(slabs).priceOf(tokenId); if (price == 0) revert NoPrice(); uint256 pay = price * sellBackBps / 10000; Pool storage pool = _pools[poolId]; uint256 free = pool.balance > pool.owedTotal ? pool.balance - pool.owedTotal : 0; if (pay > free) revert PoolCannotPay(); delete pulledBy[tokenId]; delete pulledAt[tokenId]; delete pulledFrom[tokenId]; pool.balance -= pay; _addSlab(poolId, tokenId, address(this)); emit SoldBack(poolId, msg.sender, tokenId, pay); ISlabMirror(slabs).transferFrom(msg.sender, address(this), tokenId); if (pay != 0) _sendDollars(msg.sender, pay); } // ---------------------------------------------------------------- views function poolSlabs(uint256 poolId) external view poolExists(poolId) returns (uint256[] memory tokenIds) { return _pools[poolId].slabs; } function poolInfo(uint256 poolId) external view poolExists(poolId) returns (uint256 slabCount, uint256 dollarBalance, uint256 pulls) { Pool storage p = _pools[poolId]; return (p.slabs.length, p.balance, p.pulls); } function poolDetails(uint256 poolId) external view poolExists(poolId) returns (address creator, uint256 owedTotal) { Pool storage p = _pools[poolId]; return (p.creator, p.owedTotal); } // ---------------------------------------------------------------- internals function _addSlab(uint256 poolId, uint256 tokenId, address depositor) internal { Pool storage pool = _pools[poolId]; if (pool.slabs.length >= MAX_SLABS) revert PoolFull(); _indexOf[tokenId] = pool.slabs.length; pool.slabs.push(tokenId); poolOf[tokenId] = poolId; depositorOf[tokenId] = depositor; } function _removeSlab(uint256 poolId, uint256 tokenId) internal { Pool storage pool = _pools[poolId]; uint256 i = _indexOf[tokenId]; uint256 last = pool.slabs[pool.slabs.length - 1]; pool.slabs[i] = last; _indexOf[last] = i; pool.slabs.pop(); delete _indexOf[tokenId]; delete poolOf[tokenId]; delete depositorOf[tokenId]; } function _pullDollars(address from, uint256 amount) internal { if (!IERC20Min(dollar).transferFrom(from, address(this), amount)) revert TransferFailed(); } function _sendDollars(address to, uint256 amount) internal { if (!IERC20Min(dollar).transfer(to, amount)) revert TransferFailed(); } }